Java Reference
In-Depth Information
The
APPLET
HTML tag specifies that the Java applet defined in the Java class file
HelloWorld.class
should be loaded from the web server's
applets
directory and given the
name
hello
within the current applet's context.
Returning to the topic of interapplet communication, consider two applets:
Producer
and
Consumer
.
Producer
provides an interface used by
Consumer
within the context of a sin-
gle execution environment such as a web page.
Producer
only needs to declare a method
to be used by
Consumer
, as shown in Listing 10-6.
Listing 10-6.
Declaring a Method Used by Consumer in Producer
public class Producer extends Applet {
… methods here …
public void processRequest(String anArgument) {
… do something with anArgument …
}
}
The HTML that serves the
Producer
applet must identify
Producer
so that
Consumer
can
find it by name using the
AppletContext
, as shown in Listing 10-7.
Listing 10-7.
Identifying the Producer Applet
<APPLET CODEBASE="applets/" CODE="Producer.class"
WIDTH=200
HEIGHT=200
NAME="producer"/>
The
Consumer
applet, which invokes
Producer
's
processRequest
method, only needs to
locate the
Producer
in the applet context. It can then treat the resulting object like any
other Java object, invoking its
processRequest
method, as shown in Listing 10-8.
Listing 10-8.
Invoking the Producer's processRequest Method
public class Consumer extends Applet
implements ActionListener {
… methods here …
public void actionPerformed(ActionEvent e) {
Applet producer = null;
producer = getAppletContext().getApplet("producer");
if (producer != null &&
producer instanceof Producer) {
((Producer)producer).processRequest("Hi!");