Main Page

JavaScript-to-Java communication

because it is a public method. The method simply assigns the specified string to the
message
property,
then calls
repaint()
, which clears the display of the applet and calls the
paint()
method again.
Applets only require a default constructor (which throws a
HeadlessException
if the operating system
doesn’t have a graphical interface). If the applet’s purpose is solely to provide Java functionality to
JavaScript, you can just add public methods and set the applet to a width and height of 0 in the HTML.
If, however, the applet is to display something, you most likely need to defined a
paint()
method.
After the applet is defined and saved in a file with a
.java
extension, compile the file using the
javac
utility from the command line:
javac ExampleApplet.java
This command creates a file with a
.class
extension (the previous example creates
ExampleApplet.class
). The
.class
file must be placed in a Web server directory to allow
HTML pages to access it.
JavaScript-to-Java communication
Now that you have an applet with a public method, you can include it in a Web page and access it via
JavaScript. The following example uses
ExampleApplet
from the previous section and shows how
JavaScript can be used to change the message displayed in the applet:
<html>
<head>
<title>Applet Example</title>
<script>
function changeAppletMessage() {
var oApplet = document.getElementById(“ExampleApplet”);
var oTextbox = document.getElementById(“txtMessage”);
oApplet.setMessage(oTextbox.value);
}
</script>
</head>
<body>
<p>Enter the message you want to see in the applet.</p>
<p><input type=”text” id=”txtMessage” size=”10” />
<input type=”button” value=”Set Message” onclick=”changeAppletMessage()” />
</p>
<object type=”application/x-java-applet” code=”ExampleApplet.class”
width=”100” height=”100” border=”1” id=”ExampleApplet”>
<comment>
<applet code=”ExampleApplet.class” width=”100” height=”100”
name=”ExampleApplet”></applet>
</comment>
</object>
</body>
</html>
546
Chapter 18
21_579088 ch18.qxd 3/28/05 11:43 AM Page 546


JavaScript EditorFree JavaScript Editor     Ajax Editor


©