Rhino
中使用
Java
對(duì)象
與網(wǎng)頁中所使用的
JavaScript
不同的是,
Rhino
中的腳本可以使用
Java
中的對(duì)象。要在腳本中使用
Java
類必須將
Java
類引入腳本。
使用
cx.initStandardObjects
創(chuàng)建出來的
Scriptable
類型實(shí)例,不支持在腳本中使用
import
語句,此時(shí)需要使用如下的代碼來創(chuàng)建一個(gè)
ImporterTopLevel
類的實(shí)例,它是
Scriptable
一個(gè)實(shí)現(xiàn),這樣就支持在腳本中使用
importPackage
語句:
Context cx = Context.enter();
Scriptable iptScope = new ImporterTopLevel(cx);
在腳本中如下引入包名:
importPackage(Packages.javax.swing);
如果不使用
importPackage
語句,也可以采用直接包名來使用類:
Packages.javax.swing.JFrame frame = new JFrame(“myWindow”);
?
下面的代碼演示在腳本中創(chuàng)建一個(gè)窗口,并在窗口上顯示一個(gè)按鈕。
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ImporterTopLevel;
import org.mozilla.javascript.Scriptable;
?
public class JSTest3
{
???? public static void main(String[] args)
???? {
???????? StringBuffer script = new StringBuffer();
???????? script.append("importPackage(java.awt);\n");
???????? script.append("frame = new Frame(\"JavaScript\");\n");
???????? script.append("frame.show();\n");
???????? script.append("frame.setSize(new Dimension(200,100));\n");
???????? script.append("button = new Button(\"
按鈕
\");\n");
???????? script.append("frame.add(button);\n");
???????? script.append("frame.show();\n");
?
???????? Context ctx = Context.enter();
???????? Scriptable scope = new ImporterTopLevel(ctx);
???????? try
???????? {
????????????? ctx.evaluateString(scope, script.toString(), null, 1, null);
???????? } finally
???????? {
????????????? Context.exit();
???????? }
???? }
}
運(yùn)行以后就會(huì)顯示下面的窗口: