0

Modern web pages include a wide variety of dynamic content, incorporating the use of HTML,  Javascript  and Java. I recently designed a web page that required all of these elements to work in concert, to "talk to" each other. Specifically, I had a Java applet displaying a page of text and a rollover button with a "Print" icon; when the user clicked the button, I wished the applet to print the text. Here is the solution if you wish to achieve a similar effect on your website.

To start with, code your Java applet as normal. There are no special considerations to make, other other than ensuring that the function to be called is defined as public. For instance, here is a simple function that will display a message box, showing any text passed in the szMessage parameter to the user.

public testMe(String szMessage) {<br/> JOptionPane:showMessageDialog(null, szMessage, "Hello!", JOptionPane.INFORMATION_MESSAGE); <br/>}

Compile your java file, and include it in your web page using standard HTML tags. (It is worth highlighting at this point that, if you are using a code obfuscator such as Proguard, you will need to specify that the function name be preserved after the obfuscation process).

Now, to call that function from Java, you create an HTML hyperlink in the form:

<a href="javascript:document.applets%5B0%5D.testMe(" rel="nofollow" target="_new">Click here to call a Java function.</a>

For those unfamiliar with HTML, this code creates what appears to be a standard HTML link. However, instead of changing the page, when the user clicks on the link, the browser executes a piece of  Javascript  code. The  javascript : prefix instructs the browser to execute the  Javascript ; document.applets[0] identifies the applet to "talk to" (in this case, the assumption is that this will be the first applet in the document); this is finally followed by the Java function name, including any parameters you wish to pass.

When the user clicks on the link, the correct Java function will be executed, in this case rendering a message box to the screen. As a final note, it is worth mentioning that, on tighter security settings, some browser do limit the ability of  Javascript  to "script" Java applets, and that the user may need some support to remedy this.

Post a Comment

 
Top