Thursday, June 05, 2008

Applet to applet comunication

Of course, after a talk demonstrating Applet to JavaScriipt and Applet to Flash communication the first question I had after my JavaOne session completely stumped me: how can 2 Applets on the same page communicate with each other?

Here's the solution - use the getAppletContext() method on your Applet (or JApplet) to get the context (page) of your applet and then find all the other Applets on the same page:
Enumeration e = this.getAppletContext().getApplets();
while (e.hasMoreElements()) {
Applet a = (Applet)e.nextElement();
String name = a.getName();
System.out.println("Found applet " + name);
}
Once you have a reference to an Applet instance then you can call any public method on it that you need to.

However, one of the new features in Java 6 Update 10 is to be able to specify that your Applet gets its own instance of the JVM. You can either do this explicitly with the following Applet parameter:
<param name="separate_jvm" value="true">
or your applet will get one by default if it asks for a non-standard heap size, or JNLP support.

If your applet gets its own JVM, then it will not see other Applets on the same page because they are not in its context any more - there is no longer a single global JVM context for the page, which is correct from a technical point of view, but will mean that there doesn't seem to be a reliable way to enable Applet to Applet communication without using something like JavaScript as a communication bridge between them.

No comments: