JavaFX development with just JavaScript (Nashorn)

2019-07-11 06:14发布

问题:

Is there a way to write a JavaFX app with just JavaScript files now that Nashorn is available in Java 8? Where can I find more info or videos on this? How would you compile it?

Or is there a minimal set of bootstrapping files required?

回答1:

Yes, you can develop JavaFX programs with just JavaScript (Nashorn).

How to access JavaFX from JavaScript

Use the jjs -fx yourscript.js command line switch.

The -fx flag on jjs will bootstrap scripts using a javafx.application.Application.

There is no compile step for JavaScript, just write your script and run it with jjs -fx.

There are no bootstrapping files required.

The jjs binary and the JavaFX runtime are both shipped with the Oracle Java 8 Runtime Environment (JRE) and jjs is located in the bin directory of the JRE installation.

Sample Code

A Hello World example (copied from Jim Laskey's blog).

var Button    = Java.type("javafx.scene.control.Button");
var StackPane = Java.type("javafx.scene.layout.StackPane");
var Scene     = Java.type("javafx.scene.Scene");

$STAGE.title = "Hello World!";
var button = new Button();
button.text = "Say 'Hello World'";
button.onAction = function() print("Hello World!");
var root = new StackPane();
root.children.add(button);
$STAGE.scene = new Scene(root, 300, 250);
$STAGE.show();

Additional Resources

There are numerous web examples of running JavaFX using Nashorn scripts.

  1. JavaFX with Nashorn Hello World and 3D demos
  2. JavaFX with Nashorn Canvas example.
  3. JavaFX with Nashorn Animated Gauge Demo.
  4. JavaFX with Nashorn LED readout demo.