Using Web Page Scripts to Communicate with Your Applet

On the surface, a Java applet and its host HTML page appear to have little in common. The HTML page tells the applet where to reside, but the applet acts more or less independently of its context. Even the parameters you pass to the applet appear within the <APPLET>..</APPLET> tags.

However, the line between applet and HTML blurs a bit when you introduce the idea of client-side scripts. Both JavaScript and VBScript can pass information to an applet and call an applet's methods. In this article, we'll show you the basics of script-to-applet communication.

Can't we just talk…

Although an applet is pretty much self-contained, Java offers an interface that allows you to access the methods and variables of an applet. Any public method or variable within an applet is available to a script running on the host HTML page.

This feature is quite powerful and you can use it in a number of ways. For instance, if you want to provide a specialized set of methods for your VB or Java scripts, you can develop those methods in a Java applet and simply include that applet as part of the Web page. Rather than defining all the specialized methods on the page itself, you can simply call them from the applet. Java processes your request and returns the answer to the script, which can then display the result in a standard HTML form.

Similarly, suppose you're developing an online commerce site. You want to use standard HTML forms and communications protocols to send information to a server-side database, but you want to build the store itself in Java. You could build all the commerce components into your applet and then include a submit button on the HTML page that retrieves information from your applet and passes the content to the server.

Using applets in this way also provides you a little more control over exactly who can see and manipulate your code. Finally, and perhaps most importantly, using applets and script together offers the simplest way to reuse complex code across multiple pages and sites. Instead of cutting and pasting hundreds of lines of script, you simply reference the applet containing the methods you need.

Now, let's take a peek at how you can accomplish all this magic. Although our example is a simple one, it should show you the basic steps you'll follow to communicate information between an applet and a page script.

A bevy of buttons

To illustrate our technique, we'll design a simple applet with two components--a text string and a command button. The command button will tell the applet to paint the text string at a specific location in the applet pane.

Our host HTML page will initially include a form with three components--a text input box and two buttons. One button will execute a VBScript and the other will execute a JavaScript. Both scripts do the same thing: They execute a method of the applet and pass to the applet the parameter the method needs in order to operate.

Begin by opening Developer Studio and choosing New... from the File menu. From the Projects tab of the New dialog box, choose Java Applet Wizard. Type Talker in the Project name text box and click OK to launch the Wizard.

On the first page, tell the wizard not to include source-code comments, then click Next. Again click Next to progress through the second screen of the wizard. On the third screen, tell the wizard that you don't need a multi-threaded applet and click Finish. Finally, click OK to dismiss the New Project Information dialog box and open your project.

We're ready to open the Talker.java file and make the modifications shown in Listing A. However, before we modify the HTML file, let's take a quick look at what our applet does.

Listing A: Talker.java

import java.applet.*;
import java.awt.*;

public class Talker extends Applet
{


String FormString;
Button b;

public void init()
{
    resize(320, 240);
b=new Button(ŅApplet Button");
add(b);
}
public boolean action(Event evt, Object arg)
{
if (evt.target==b)
PutItIn(ŅApplet Button");
return true;
}

public void paint(Graphics g)
{
g.drawString(FormString, 10, 20);
}
public void PutItIn(String s)
{
FormString=s;
repaint();
}

}

We create a String variable to hold the text that we'll paint on the applet pane. We also create a button that tells the applet to paint the text on the applet.

The action() method responds to the button click and fires the PutItIn() method. Finally, the PutItIn() method receives a string as an argument, sets the FormString variable equal to the string it receives, and calls the repaint() method.

The page scripts

Now that we have the applet out of the way, let's work on the page scripts. Open Talker.html. So that we can better identify the applet area on the page, change the <body> tag to read

<body bgcolor = "white">

Next, eliminate the line

<a href="Talker.java">The source.</a>

near the bottom of the file. At this point, we're ready to build the form we'll use to hold the HTML input controls.

Immediately above the </body> tag, type the following form definition:

<form name="HTMLFORM">
<input type="button" value="JavaScript SendIt" onClick="doIt()">
<input type="button" name="VBBUTTON" value="VBScript SendIt">
<input type="text" name="textField">
</form>

This form defines two buttons. Because we'll use one button to fire a VBScript and the other to fire a JavaScript, we define the buttons differently. The JavaScript button includes an onClick value that instructs the browser to execute the doIt() JavaScript function when the user clicks the button.

The VBScript button doesn't include an onClick definition; instead, we'll develop an onClick handler in the VBScript itself. However, since the VBScript handler needs to know the source of the event it's handling, we'll explicitly name our button VBBUTTON.

Our text field doesn't really do much. We assign it a name so we'll be able to easily reference it in the scripts. We name the form, as well, so we can build a more intuitive reference to the value of the text field.

Next, let's build the JavaScript. Following the </form> tag, add the code shown below:

<script language="javascript">
function doIt()
{
document.Talker.PutItIn
(document.HTMLFORM.textField.value);
}
</script>

This script first declares the function doIt(). Then, it defines the function's single action--a method call to the PutItIn() method of the Talker applet. The syntax

document.Talker.PutItIn()

reveals that JavaScript recognizes the applet and its methods as being a part of the document collection. Similarly, to generate the string that the PutItIn() method needs as a parameter, the script references the value property of the textField text input (a part of the HTMLFORM form), which is part of the document collection.

Next, let's define the VBScript. To do so, add the following code after the </script> tag:

<script language="vbscript">
Sub VBBUTTON_onClick
Call document.Talker.PutItIn
(document.HTMLFORM.textField.value)
End Sub
</script>

As you can see, this script works very much like our JavaScript. We create a subroutine that fires when the VBBUTTON button sends the onClick event. The VBScript refers to the objects and methods in question in the same way as the JavaScript. However, we must use the call keyword to execute the applet's PutItIn() method.

Listing B shows the complete listing for Talker.html. Now that we've done all the hard work, let's have a little fun.

Listing B: Talker.html

<html>
<head>
<title>Talker</title>
</head>
<body bgcolor="white">
<hr>
<applet
    code=Talker.class
    name=Talker
    width=320
    height=240 >
</applet>
<hr>
<form name="HTMLFORM">
<input type="button" value="JavaScript SendIt" onClick="doIt()">
<input type="button" name="VBBUTTON" value="VBScript SendIt">
<input type="text" name="textField">
</form>
<script language="javascript">
function doIt()
{
document.Talker.PutItIn
(document.HTMLFORM.textField.value);
}
</script>
<script language="vbscript">
Sub VBBUTTON_onClick
Call document.Talker.PutItIn
(document.HTMLFORM.textField.value)
End Sub
</script>

</body>
</html>

Running the applet

To build and execute Talker.java, press [Ctrl]F5. Developer Studio will launch Internet Explorer and load both Talker.html and the Talker applet. As Figure A shows, when the applet loads, the textField field is empty and the applet pane includes no text.

Our sample applet loads and displays both the HTML and Java buttons.

Now, type JavaScript into the text field and click the JavaScript SendIt button. As Figure B shows, JavaScript successfully executes the applet's PutItIn() method and passes to it the value from the text field in the HTML form.

The JavaScript worked as expected.

Lest you think that JavaScript and Java work better together because they are more kindred spirits than are Java and VBScript, type VBScript in the text field and click the VBScript SendIt button. As Figure C shows, the VBScript also calls the PutItIn() method with no trouble.

We can also use VBScript to talk to our applet.

Retrieving applet information

So far, we've demonstrated that you can execute the methods of an applet from page scripts. Now, let's look at the process you use to retrieve information from the applet for use on your HTML page. We'll add a third button to the HTML page that executes a second JavaScript function. This function will retrieve the value of the FormString variable from the applet and write it into the HTML form's text field.

To begin, close Internet Explorer and open Talker.HTML. Then, add the following button definition immediately after the VBBUTTON definition:

<input type="button" value="GetIt" onClick="getIt()">

As before, this definition tells the browser to execute the getIt() function when the user clicks the button.

Next, let's build the getIt() function. Following the closing brace (}) of the doIt() function, type the lines

function getIt()
{
document.HTMLFORM.textField.value=
document.Talker.FormString;
}

This function simply sets the value of the form's text field to the value of the applet's FormString variable. Now, let's test the new function.

The second time around

To execute the applet, press [Ctrl]F5. When the applet loads, click the Applet Button button to paint the text Applet Button on the applet pane. Then, click the GetIt button on the HTML form. As Figure D shows, the applet passes the value of the FormString variable to the HTML form's text field.

The JavaScript applet retrieved the value of the public variable FormString.

The privacy issue

As we mentioned, you can access the public methods and data members of an applet through page scripts. You've probably already determined that, conversely, you can't access the private methods or variables of an applet. For example, if we change our variable declaration from

string FormString;

to

private String FormString

the GetIt button on our HTML form will no longer work. It simply won't be able to retrieve the value of the private FormString variable.

However, if you call a public applet method that in turn executes private methods or uses private data, your page scripts will still work. Suppose, for instance, that you declare the applet's repaint() method as private. The VBScript SendIt button on the form will be able to paint information to the applet pane because it calls the public PutItIn() method, which in turn calls the private repaint() method.