Access Java variables from JavascriptTag(s): Javascript interaction


Java variables can be used by giving the fully qualified name. In Java, the variable must be declared as "public". To be compatible Netscape AND MSIEv4, the preferred way is to use special "access method" to read Java variables (only String or integer).

[Java applet]

import java.awt.*;
import java.applet.*;
public class InJava3 extends Applet{
  public int     iJava = 123;
  public String  sJava = "String from JAVA";

  public int getIntJava() {
      return iJava;
      }
  public String getStringJava() {
     return sJava;
     }
}

[Javascript and HTML]

<HTML><HEAD></HEAD><BODY>
<SCRIPT>
function JavaSays() {
   alert("Java says\n the value of iJava is :" +
         document.myApplet.getIntJava() + "\n" +
         "and sJava is :" +      
         document.myApplet.getStringJava());
   }
</SCRIPT>
<FORM>
<INPUT type="button" value="Java says" 
   onClick = "JavaSays();">
</FORM>
<APPLET CODE="InJava3.class"  
        NAME="myApplet" 
        HEIGHT=0 WIDTH=0>
</APPLET></BODY></HTML>
Try it here

Remember that IE4 can access only attributes and methods from a class derived from java.applet.Applet. If you want to call a method or use an attribute in another class, you have to create a method in your applet class that calls the other class's method.


blog comments powered by Disqus