Main Page

Writing applets

}
var oApplet = getApplet(“ExampleApplet”);
After you have a reference to the applet, you can actually access all the applet’s public methods directly
from JavaScript, such as:
oApplet.appletPublicMethod();
This opens up all kinds of functionality to JavaScript by using a Java applet as a host environment;
JavaScript can control anything that can be done within the applet.
Writing applets
To write a Java applet, you must first download the Java Development Kit (JDK) from Sun’s Web site
(
http://java.sun.com/j2se/
). It is up to you whether you use a development environment or a
plain text editor to write the applet, but all applets have one thing in common: they must inherit from
java.applet.Applet
. (You can, however, create a Swing-based Java applet by inheriting from
javax.swing.JApplet
, which inherits from
java.applet.Applet
).
Here’s a small example applet:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.HeadlessException;
public class ExampleApplet extends Applet {
private String message = “Hello World!”;
public ExampleApplet() throws HeadlessException {
super();
}
public void paint(Graphics g) {
g.drawString(message, 20, 20);
}
public void setMessage(String message) {
this.message = message;
repaint();
}
}
This applet simply displays the text
“Hello World!”
on the applet. The
paint()
method controls
what is displayed when the applet is first loaded, and it receives a
Graphics
object as its sole argument.
The
Graphics
object is a representation of the visual area of the applet with methods to draw onto the
applet, such as
drawString()
, which draws the given text at the x and y coordinates specified.
The applet defined previously also has a private property called
message
, which is initialized to
“Hello
World!”
This property can be changed by calling
setMessage()
, which is accessible from JavaScript
545
Interacting with Plugins
21_579088 ch18.qxd 3/28/05 11:43 AM Page 545


JavaScript EditorFree JavaScript Editor     Ajax Editor


©