How to extend Java class in Nashhorn JavaScript an

2019-09-07 22:33发布

I try to create an instance of a class that extends a Java class, and in that instance add some class member variables. 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"

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.

(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.

2条回答
迷人小祖宗
2楼-- · 2019-09-07 23:27

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). It does not allow you to add arbitrary properties, at least according to the documentation. See The Nashorn Java API, which says:

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)

You are attempting to add an object as a property of the class, at least the way your code is presently written.

查看更多
冷血范
3楼-- · 2019-09-07 23:28

javax.swing.JCheckBox instead of JCheckBox ?

查看更多
登录 后发表回答