如鹏网 大学生计算机学习社区

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开源团队 阅读(883) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: