Sunday, September 4, 2011

Javascript to Applet Communication - Example 2

I have found another article on this topic where the code works and I shall cite it here because the Java code is simpler and therefore perhaps more elegant than the previous one.

import javax.swing.*;
import netscape.javascript.JSObject;

public class JSHelloWorld extends JApplet {
JTextArea txt = new JTextArea(100,100);
public JSHelloWorld() {
txt.setText("Hello World");
getContentPane().add(txt);
}

public void setText(String s)
{
txt.setText(s);
}
}

The HTML, on the other hand is a bit more wordy, because the Applet and the JavaScript form are laid out side by side, but I like it:

<html>
<body>
<script type="text/javascript">
function updateApplet()
{
document.jsap.setText(document.forms[0].txt1.value);
}
</script>
<form>
<table border=0 align='center' cellpadding=0 cellspacing=0 >
<tr><td valign='top' width=180>
<table>
<tr><td style='text-align:center; background-color:#EEEEEE'>Applet</td></tr>
<tr><td><applet code="JSHelloWorld.class"
width="180" height="180" MAYSCRIPT style="border-width:0;" name="jsap" id="jsap">
</applet> </td></tr></table>
</td><td valign='top' width=180>
<table width=180>
<tr><td style='text-align:center; background-color:#EEEEEE'>JavaScript</td></tr>
<tr><td><textarea style='width:180px; height:150px' name='txt1'>Type and click!</textarea></td></tr>
<tr><td align='center'><input type=button value='Update applet' onClick='updateApplet()'></td></tr>
</table>
</td></tr>
</form>
</body>
</html>

This comes up as shown below.

You can then type something into the box on the form, or you can leave it as it is and click the button. It then becomes as shown below.

Full original versions of the code can be downloaded from this page.

No comments: