Calling Java from JavaScript
The Mozilla Rhino JavaScript interpreter bundled with Arbortext Editor provides a mechanism called LiveConnect that lets you use Java classes and methods from JavaScript. The Arbortext Object Model (AOM) classes are written in Java and made available in JavaScript by LiveConnect.
LiveConnect manages the Java to JavaScript communication, including conversion of data types. JavaScript: The Definitive Guide, written by David Flanagan and published by O'Reilly, discusses this subject. There are some limitations with LiveConnect and the AOM, as noted in
JavaScript Limitations.
Rhino also supports defining new JavaScript classes by writing Java code that extends the
org.mozilla.javascript.ScriptableObject class. The JavaScript function
defineClass makes such classes available to JavaScript. Refer to the Rhino documentation at the Mozilla web page (
www.mozilla.org/rhino/doc.html) for details.
With LiveConnect, Java packages are represented in JavaScript by the
JavaPackage class. You can access the Java classes provided with the JVM embedded in
Arbortext Editor, plus those found in the Java class path (as specified by the
javaclasspath parameter of the
setOption method, described in
AOM set Options Overview) from the top-level JavaPackage object
Packages. This includes the standard Java system classes (for example,
Packages.java.lang.System) and the packages provided by
Arbortext (for example,
Packages.com.arbortext.epic,
Packages.org.w3c.dom), and the JavaScript interpreter (
Packages.org.mozilla.javascript). As a convenience, the classes in the
java package can be referred to directly without the
Packages qualifier, for example,
java.lang.System and
java.lang.awt.Frame.
|
The Java Swing classes are in the javax package, so you must fully qualify the package name (Packages.javax.swing) to use Swing classes.
|
The global object Application is a shortcut for the Packages.com.arbortext.epic.Application JavaClass. Similarly, the global object Acl is a shortcut for the Packages.com.arbortext.epic.Acl JavaClass.
The following JavaScript example uses the standard Java AWT classes to create and display a dialog box.
|
Since no event handling is specified in this example, the dialog box cannot be dismissed.
|
function hello()
{
var f = new java.awt.Frame("Hello World");
var ta = new java.awt.TextArea("hello, world", 100, 200);
f.add("Center", ta);
f.pack();
f.show();
}
hello();
A more complicated example with event handling is included with the
Arbortext distribution. Refer to
Sample JavaScript Code for details.