Trail: Deployment
Lesson: Applets
Section: Doing More With Applets
Sending Messages to Other Applets
Home Page > Deployment > Applets
Sending Messages to Other Applets

Applets can find other applets and send messages to them, with the following security restrictions:


Note:  Some browsers let applets invoke methods on other applets, even applets on different pages in the same browser, as long as all of the applets come from the same code base. This method of interapplet communication is not supported by the Java API, so it might not be supported by all browsers.

An applet can find another applet either by looking it up by name (by using the AppletContext getApplet method) or by finding all the applets on the page (using the AppletContext getApplets method). Both methods, if successful, give the caller one or more Applet objects. Once the caller finds an Applet object, the caller can invoke methods on the object.

Finding an Applet by Name: The getApplet Method

The getApplet method checks all the applets on the current page to determine if one of them has the specified name. If so, getApplet returns the applet's Applet object.

By default, an applet has no name. For an applet to have a name, the name must be specified in the HTML code that adds the applet to a page. You can specify an applet's name in two ways:

See Deploying an Applet for more information about the runApplet function.


Browser Note:  Although at least one browser enabled with Java technology conducts a case-sensitive search, the expected behavior is for the getApplet method to perform a case-insensitive search. For example, getApplet("old pal") and getApplet("OLD PAL") should both find an applet named "Old Pal".

The following are two applets that illustrate how applets are found by name. The first applet, the Sender finds the second applet, the Receiver. When the Sender finds the Receiver, the Sender sends a message to the Receiver by invoking one of the Receiver's methods (passing the Sender's name as an argument). The Receiver reacts to this method call by changing its leftmost text string to "Received message from sender-name!".




Note: If you don't see the applet running, make sure that you have at least the Java 2 Platform, Standard Edition (J2SE) 1.4.2 release on your client. If not, download and install the latest release of the Java SE Development Kit (JDK).

Note: If you don't see the example running, you might need to enable the JavaScript interpreter in your browser so that the Deployment Toolkit script can function properly.

Try this:  Click the Send message button of the top applet (the Sender). Some status information will appear in the Sender's window, and the Receiver will confirm (with its own status string) that it received a message, After you have read the Receiver status string, press the Receiver's Clear button to reset the Receiver. In the Sender's text field labeled "Receiver name:," type in buddy and press Return. Since "buddy" is the Sender's own name, the Sender will find an applet named "buddy" but will not send it a message, since it is not a Receiver instance.

The Sender uses the following code to find and communicate with the Receiver.

Applet receiver = null;
String receiverName = nameField.getText(); //Get name to search for.
receiver = getAppletContext().getApplet(receiverName);

The Sender makes sure that the Receiver was found and that it is an instance of the correct class (Receiver). If all conditions are met, the Sender sends a message to the Receiver.

if (receiver != null) {
    //Use the instanceof operator to make sure the applet
    //we found is a Receiver object.
    if (!(receiver instanceof Receiver)) {
        status.appendText("Found applet named "
                          + receiverName + ", "
                          + "but it's not a Receiver object.\n");
    } else {
        status.appendText("Found applet named "
                          + receiverName + ".\n"
                          + "  Sending message to it.\n");
        //Cast the receiver to be a Receiver object
        //(instead of just an Applet object) so that the
        //compiler will let us call a Receiver method.
        ((Receiver)receiver).processRequestFrom(myName);
    }
} . . .

See the complete source code for the Sender and Receiver for more detail.

The example applets in this page perform a one-way communication from the Sender to the Receiver. If you want your Receiver to be able to send messages to the Sender, then have the Sender give a reference to itself (this) to the Receiver. For example:

((Receiver)receiver).startCommunicating(this);

Download source code for the Sender Receiver Applets example to experiment further.

Finding All the Applets on a Page: The getApplets Method

The getApplets method returns a list (an Enumeration, to be precise) of all the applets on the page. For security reasons, many browsers implement getApplets so that it returns only those applets that originated from the same host as the applet calling getApplets. Here is an applet that lists all the applets it can find on this page:


Note: If you don't see the applet running, make sure that you have at least the Java 2 Platform, Standard Edition (J2SE) 1.4.2 release on your client. If not, download and install the latest release of the Java SE Development Kit (JDK).

The following are relevant parts of the GetApplets class that invokes the getApplets method..

public void printApplets() {
    //Enumeration will contain all applets on this page (including
    //this one) that we can send messages to.
    Enumeration e = getAppletContext().getApplets();
    . . .
    while (e.hasMoreElements()) {
        Applet applet = (Applet)e.nextElement();
        String info = ((Applet)applet).getAppletInfo();
        if (info != null) {
            textArea.appendText("- " + info + "\n");
        } else {
            textArea.appendText("- "
                                + applet.getClass().getName()
                                + "\n");
        } 
    }
    . . . 
}

Download source code for the Get Applets in a Page example to experiment further.

Previous page: Writing Diagnostics to Standard Output and Error Streams
Next page: Working With a Server-Side Application

Discuss
We welcome your participation in our community. Please keep your comments civil and on point. You may optionally provide your email address to be notified of replies — your information is not used for any other purpose. By submitting a comment, you agree to these Terms of Use.