简体   繁体   English

如何在Nashhorn JavaScript中扩展Java类并添加类成员变量

[英]How to extend Java class in Nashhorn JavaScript and add class member variables

I try to create an instance of a class that extends a Java class, and in that instance add some class member variables. 我尝试创建扩展Java类的类的实例,然后在该实例中添加一些类成员变量。 Here's my attempt: 这是我的尝试:

var ui = Java.extend(javax.swing.JPanel, { 
    cb : new JCheckBox("A checkbox", true),
});

However, the Nashorn interpreter throws this error: "TypeError: function noSuchMethod () { [native code] } is not a constructor function" 但是,Nashorn解释器将引发此错误:“ TypeError:function noSuchMethod (){[native code]}不是构造函数”

What am I doing wrong? 我究竟做错了什么? Nashorn didn't complain when I added an instance of a custom class, like se.datadosen.util.Stopwatch, but it throws this error when I try to add that JCheckBox. 当我添加一个自定义类的实例(例如se.datadosen.util.Stopwatch)时,Nashorn并没有抱怨,但是当我尝试添加该JCheckBox时,它将引发此错误。

(I know components are added to panels with the .add() call, but this question is really about how to add class member variables to a subclass. (我知道组件是通过.add()调用添加到面板的,但是这个问题实际上是关于如何将类成员变量添加到子类的。

javax.swing.JCheckBox而不是JCheckBox?

Java.extend allows you to add methods implemented in JavaScript to a Java class (actually, to create a new class that subclasses the Java class). Java.extend允许您将用JavaScript实现的方法添加到Java类中(实际上是创建一个新类来Java.extend Java类)。 It does not allow you to add arbitrary properties, at least according to the documentation. 至少根据文档,它不允许您添加任意属性。 See The Nashorn Java API , which says: 请参阅Nashorn Java API ,其中说:

You can extend a class using the Java.extend() function that takes a Java type as the first argument and method implementations (in the form of JavaScript functions) as the other arguments." (emphasis added) 您可以使用Java.extend()函数扩展一个类,该函数将Java类型作为第一个参数,并将方法实现(以JavaScript函数的形式)作为其他参数。”(添加了重点)

You are attempting to add an object as a property of the class, at least the way your code is presently written. 您正在尝试将对象添加为类的属性,至少是当前编写代码的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM