如鵬網 大學生計算機學習社區

          CowNew開源團隊

          http://www.cownew.com 郵件請聯系 about521 at 163.com

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            363 隨筆 :: 2 文章 :: 808 評論 :: 0 Trackbacks

          Rhino 中使用 Java 對象

          與網頁中所使用的 JavaScript 不同的是, Rhino 中的腳本可以使用 Java 中的對象。要在腳本中使用 Java 類必須將 Java 類引入腳本。

          使用 cx.initStandardObjects 創建出來的 Scriptable 類型實例,不支持在腳本中使用 import 語句,此時需要使用如下的代碼來創建一個 ImporterTopLevel 類的實例,它是 Scriptable 一個實現,這樣就支持在腳本中使用 importPackage 語句:

          Context cx = Context.enter();

          Scriptable iptScope = new ImporterTopLevel(cx);

          在腳本中如下引入包名:

          importPackage(Packages.javax.swing);

          如果不使用 importPackage 語句,也可以采用直接包名來使用類:

          Packages.javax.swing.JFrame frame = new JFrame(“myWindow”);

          ?

          下面的代碼演示在腳本中創建一個窗口,并在窗口上顯示一個按鈕。

          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();

          ???????? }

          ???? }

          }

          運行以后就會顯示下面的窗口:

          ri1.JPG

          posted on 2007-01-03 21:17 CowNew開源團隊 閱讀(895) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 沁水县| 云安县| 故城县| 马鞍山市| 南澳县| 来宾市| 天津市| 罗江县| 奎屯市| 绩溪县| 明光市| 新邵县| 洪雅县| 余庆县| 清镇市| 云南省| 星座| 孟村| 刚察县| 富顺县| 新化县| 乐安县| 清水河县| 沙河市| 文化| 宝鸡市| 登封市| 成安县| 郑州市| 浮山县| 色达县| 桦甸市| 南木林县| 张家界市| 新竹县| 上饶市| 深圳市| 南丹县| 三原县| 宕昌县| 靖边县|