问题
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.
回答1:
javax.swing.JCheckBox instead of JCheckBox ?
回答2:
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.
来源:https://stackoverflow.com/questions/25996675/how-to-extend-java-class-in-nashhorn-javascript-and-add-class-member-variables