Wednesday, March 3, 2010

How to call a JavaScript function from a Java applet




Calling a JavaScript function from a Java applet is really simple; in order to approach it we need to use the showDocument method, see the example below of the Java applet:

import java.net.*;
import java.applet.*;


public class MyApplet extends Applet
{
public void init()
{
String msg = "Hello World...";

try {
URL _url = new URL("javascript: callme(\"" msg "\")"
getAppletContext().showDocument( _url) );
}
catch (MalformedURLException e) {
e.toString();
}
}
}


Next we need the JavaScript function:

<script language="JavaScript" type="text/javascript">
function callme(msg)
{
try{
alert(msg);
}
catch(e){
alert(e);
}
}
</script>

Finally we code the HTML code:

<APPLET CODE="MyApplet.class"
NAME="myApplet"
MAYSCRIPT
HEIGHT=15
WIDTH=15>
</APPLET>




No comments:

Post a Comment