Previous | Next | Trail Map | Writing Applets | Communicating with Other Programs


Sending Messages to Other Applets On the Same Page

Applets can find other applets and send messages to them, with the following security restrictions: An applet can find another applet either by looking it up by name (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.

Below are two applets that illustrate the point. The first, Sender, looks up the second, 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 left-most text string to "Received message from Sender name!".

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've read the Receiver status string, press the Receiver's Clear button to reset the Receiver.

Note: If you see "Couldn't find any applet named Old Pal" in the Sender status field, then you've probably run into a browser bug. Under the Netscape Navigator 2.0 browser, getApplet() often fails when it should succeed. The Sender works around this bug by invoking getApplets() if getApplet() fails. This workaround is explained in more detail later in this page.

Try this (if your browser correctly implements getApplet()): 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 won't send it a message, since it isn't a Receiver instance.

Finding an Applet by Name: The getApplet() Method

This section gives you the code the Sender uses to look up an applet by name. (Here's the whole Sender program.) Code that you can use without change in your own applet is in bold font.
Applet receiver = null;
String receiverName = nameField.getText(); //get name to search for
receiver = getAppletContext().getApplet(receiverName);
The Sender goes on to make sure that the Receiver was found and that it's an instance of the correct class (Receiver). If all goes well, the Sender sends a message to the Receiver. (Here's the Receiver program.)
if (receiver != null) {
    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");
        ((Receiver)receiver).processRequestFrom(myName);
    }
} . . .
Because some browsers don't implement getApplet() correctly, the applet doesn't give up if receiver is null. Instead, it calls the getApplets() method, as the next section describes.

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

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

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 and applet viewers implement getApplets() so that it returns only those applets that originated from the same host as the applet calling getApplets(). Here's an applet that simply lists all the applets it can find on this page:

Below are the relevant parts of the method that calls getApplets(). (Here's the whole program.)

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");
        } 
    }
    . . . 
}

In the first example on this page, when the Sender applet can't find the Receiver, it assumes that it might be due to the Netscape bug. Since Netscape implements getApplets(), the Sender tries that as a workaround. This implementation of Sender simply sends a processRequestFrom() message to the first Receiver getApplets() returns. It probably should be more careful; it should check the Receiver's name (which would require adding a method to the Receiver class) before sending the Receiver a processRequestFrom() message.

Here's the code the Sender uses when getApplet() fails to return anything:

public void searchAllApplets() {
    Enumeration appletList = getAppletContext().getApplets();
    boolean foundReceiver = false;

    while (appletList.hasMoreElements() && !foundReceiver) {
        Applet applet = (Applet)appletList.nextElement();
        if (applet instanceof Receiver) {
            status.appendText("  Found Receiver applet.\n"
                              + "  Sending message to it.\n");
            ((Receiver)applet).processRequestFrom(myName);
        }
    }
}


Previous | Next | Trail Map | Writing Applets | Communicating with Other Programs