Mega Code Archive

 
Categories / JavaScript DHTML / Development
 

Using JavaScript in an Applet

/* Mastering JavaScript, Premium Edition by James Jaworski  ISBN:078212819X Publisher Sybex CopyRight 2001 */ <title>Accessing JavaScript from an applet</TITLE> <form NAME="textForm"> <P>Enter some text and then click Display Text:  <INPUT TYPE="text" NAME="textField" SIZE="20"></P> </FORM> <APPLET CODE="ReadForm.class" WIDTH=400 HEIGHT=100  NAME="readApp" MAYSCRIPT> [The ReadForm Applet] </APPLET> //Reading a JavaScript Form (ReadForm.java) import java.applet.*; import java.awt.*; import java.awt.event.*; import netscape.javascript.JSObject; import netscape.javascript.JSException; public class ReadForm extends Applet {  String text="Enter some text for me to display!";  Font font = new Font("TimesRoman",Font.BOLD+Font.ITALIC,24);  JSObject win, doc, form, textField;  public void init() {   win = JSObject.getWindow(this);   doc = (JSObject) win.getMember("document");   form = (JSObject) doc.getMember("textForm");   textField = (JSObject) form.getMember("textField");   setLayout(new BorderLayout());   Panel buttons = new Panel();   Button displayTextButton = new Button("Display Text");   displayTextButton.addActionListener(new ButtonEventHandler());   buttons.add(displayTextButton);   add("South",buttons);  }  public void paint(Graphics g) {   g.setFont(font);   g.drawString(text,30,30);  }  class ButtonEventHandler implements ActionListener {   public void actionPerformed(ActionEvent e){    String s = e.getActionCommand();    if("Display Text".equals(s)) {     text= (String) textField.getMember("value");     win.eval("alert(\"This alert comes from Java!\")");     repaint();    }   }  } }