Wednesday, April 28, 2010

How to invoke a Java method from JavaScript

It's surprisingly easy. Basically the applet you declare in the <applet> tag sets up the Java class as an object that can be referenced with standard DOM calls.

For the purpose of this example, I'm not displaying anything with the sample applet, only returning values from method calls, so the code doesn't import awt or Swing, only java.applet.Applet.

Here is a sample java class that exposes two methods, add and subtract:
package cea.demos;

import java.applet.Applet;
public class Arithmetic extends Applet {

  public int add(int x, int y) {
    return x + y;
  }

  public int subtract(int x, int y) {
    return x - y;
  }
}

The above code is compiled in the library http://sites.google.com/site/ceauterytest/Home/cea.jar as cea/demos/Arithmetic.class. From JavaScript, I want to reference it as arithApplet. The applet that I declare is:
<applet code="cea/demos/Arithmetic.class"
 archive="http://sites.google.com/site/ceauterytest/Home/cea.jar"
 width=0 height=0 name="arithApplet">
</applet>
Pretty straitforward. Height and width are 0, because the applet doesn't need to draw anything. To call the methods in the class, I invoke them as arithApplet.add() and arithApplet.subtract(), as shown in this sample HTML:
<html><body>
<applet code="cea/demos/Arithmetic.class"
 archive="http://sites.google.com/site/ceauterytest/Home/cea.jar"
 width=0 height=0 name="arithApplet">
</applet>

<script>
function delegateAdd(x, y) {
  outForm.answer.value = arithApplet.add(x.value, y.value);
}

function delegateSubtract(x, y) {
  outForm.answer.value = arithApplet.subtract(x.value, y.value);
}
</script>

<form name=inForm>
  <input type=text size=4 name=x><br>
  <input type=text size=4 name=y>
  <input type=button value="+" onclick="delegateAdd(inForm.x, inForm.y)">
  <input type=button value="-" onclick="delegateSubtract(inForm.x, inForm.y)">
</form>
<br><br>
<form name=outForm>
  <input type=text size=5 name=answer>
</form>

</body></html>
Obviously this is only useful as an illustration, unless adding and subtracting is your thing, but a functioning demo is available here.

No comments:

Post a Comment