如鵬網(wǎng) 大學(xué)生計(jì)算機(jī)學(xué)習(xí)社區(qū)

          CowNew開源團(tuán)隊(duì)

          http://www.cownew.com 郵件請聯(lián)系 about521 at 163.com

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

          Rhino 中使用 Java 對象

          與網(wǎng)頁中所使用的 JavaScript 不同的是, Rhino 中的腳本可以使用 Java 中的對象。要在腳本中使用 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ì)顯示下面的窗口:

          ri1.JPG

          posted on 2007-01-03 21:17 CowNew開源團(tuán)隊(duì) 閱讀(894) 評論(0)  編輯  收藏

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


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 绩溪县| 邓州市| 拉萨市| 樟树市| 建瓯市| 修水县| 大城县| 杨浦区| 和林格尔县| 永登县| 信宜市| 新巴尔虎右旗| 赤峰市| 宜川县| 外汇| 安阳市| 陆河县| 措美县| 曲麻莱县| 贵溪市| 滨海县| 太保市| 台湾省| 白山市| 邢台市| 无极县| 泽普县| 揭西县| 乳山市| 沙河市| 蒙山县| 开化县| 拉萨市| 奉贤区| 湟源县| 卢湾区| 桐柏县| 二连浩特市| 宜君县| 奎屯市| 榆树市|