Question

I am experimenting with using JavaFX 2 from JavaScript through the JavaScripting API (Rhino).

Note: This is a rich-client question, nothing to do with web-programming.

I would like to orchestrate some parts of my JavaFX rich-client application with dynamic scripts. I am evaluating if the JavaScripting API with the bundled JavaScript Runtime (Rhino) would be a good approach for my requirements.

So my first attempt was to create a simple JavaFX-GUI through JavaScript:

print('Starting...')

importPackage(Packages.javafx.scene);
importPackage(Packages.javafx.scene.layout);
importPackage(Packages.javafx.stage);
importClass(Packages.javafx.scene.layout.StackPane);
importClass(Packages.javafx.scene.Scene);
importClass(Packages.javafx.stage.Stage);

myroot = new Packages.javafx.scene.layout.StackPane();
myscene = new Packages.javafx.scene.Scene(myroot);
mystage = new Packages.javafx.stage.Stage();
mystage.setScene(myscene);
mystage.show();

I am then running this script with jsrunscript. The inspiration for that script came from the Oracle documentation.

However the script already fails at line 4:

> ☹ jrunscript -f script.js                                             
> Starting...script error in file script.js :
> sun.org.mozilla.javascript.internal.EvaluatorException: Function importClass must be called with a class; had "[JavaPackage javafx.scene.layout.StackPane]" instead. (script.js#4) in script.js at line number 6

It looks like I can't import the JavaFx package/classes into the javascript runtime. Although the oracle documentation states to this with java.awt.

What am I doing wrong?

Was it helpful?

Solution

I advise using the Nashorn script engine with the jjs -fx command running JavaScript coded JavaFX scripts.

  • Nashorn is a much more modern JavaScript engine than Rhino.
  • Nashorn has convenience features for launching JavaFX JavaScript scripts.
  • Nashorn is included in Java 8 and Rhino will be removed from Java 8.

There is an example of using Nashorn with JavaFX which should help you get started.

Java 8 early access releases including Nashorn and JavaFX can be downloaded from: https://jdk8.java.net/download.html


Regarding your JavaFX runtime issue, it is probably because you are using Java7 where the JavaFX runtime is not on your runtime classpath. Search your JRE location for jfxrt.jar and add the location returned to your runtime classpath. This is not an issue with Java 8, which includes JavaFX on the runtime classpath.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top