Real'sHowTo AddThis Feed Button
Custom Search

Call a Java method from JavascriptTag(s): Javascript interaction


You call a Java method by giving its fully qualified name. In the following snippet, the first example calls the method in the Toolkit to retrieve the screen resolution. The second example, calls a method in our Applet.

NOTE: On IE4 or better, you can't call java.* methods directly from Javascript or Jscript. IE javascript can only access the public methods of an applet (a class derived from java.applet.Applet) but don't have a general access to other java classes . So the solution is simple, wrap the java.* call in a public method of a "dummy" Applet.

[Java applet]

import java.awt.*;
import java.applet.*;
public class InJava extends Applet{
  public void sayHello() {
    Graphics g = getGraphics();
    g.drawString("Hello from JAVA!", 10, 10);
    }
}

[Javascript and HTML (Netscape)]

<HTML><HEAD></HEAD><BODY>
<SCRIPT>
function getScreenDimension() {

alert("Screen Dimension\n" +
  "  width:" +
  java.awt.Toolkit.getDefaultToolkit().getScreenSize().width +
  " height:" +
  java.awt.Toolkit.getDefaultToolkit().getScreenSize().height);
  }
</SCRIPT>
<FORM>
<INPUT type="button" value="call Java Applet method"
   onClick = "document.myApplet.sayHello()">
</FORM>

<INPUT type="button" value="call Java method direct"
   onClick = "getScreenDimension()">

<APPLET CODE="InJava.class"
        NAME="myApplet"
        HEIGHT=100 WIDTH=100>
</APPLET>
</BODY></HTML>
Try it here

import java.awt.*;
import java.applet.*;
// (IE and Netscape ok)
public class InJava2 extends Applet{
  public int getScreenWidth() {
    return Toolkit.getDefaultToolkit().getScreenSize().width;
  }
  public int getScreenHeight() {
    return Toolkit.getDefaultToolkit().getScreenSize().height;
  }
}

[Javascript and HTML (IE and Netscape)]

<HTML><HEAD></HEAD><BODY>
<SCRIPT>
function getScreenDimension() {
   alert("Screen Dimension\r\n  width:" +
         document.myApplet.getScreenWidth() +
         " height:" +
        document.myApplet.getScreenHeight() );
   }
</SCRIPT>
<FORM>
<INPUT type="button" value="call JAVA"
   onClick = "getScreenDimension()">
</FORM>
<APPLET CODE="InJava2.class"
        NAME="myApplet"
        HEIGHT=100 WIDTH=100>
</APPLET>
</BODY></HTML>
Try it here

NOTE: This for demonstration only. On N4 or IE4, it's better to use screen.height and screen.width properties directly. There is no need for a Java Applet!

NOTE: The first time, there is a delay because the Applet need to load and initialize.


blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2014
[ home ]