3 Nashorn and JavaFX

This chapter describes how to create and run JavaFX applications using scripts interpreted by the Nashorn engine. It is assumed that you are familiar with JavaFX. For more information, see the JavaFX documentation at http://docs.oracle.com/javase/8/javafx/

You can interpret a JavaFX script application with Nashorn using the jjs command with the -fx option. For example, the following command invokes Nashorn to interpret the JavaFXscript.js file:

A JavaFX script application is similar to the Java equivalent, but Nashorn enables you to simplify many of the JavaFX constructs. Typically, a JavaFX script application contains only the start() function, which is equivalent to the start() method in its Java counterpart. It can also contain the init() and stop() functions.

Example 3-1 contains the source code for a simple JavaFX application that displays a button, which when clicked prints "Hello World!" to standard output.

Both Example 3-1 and Example 3-2 produce the same result: a window titled Hello World! with a button labeled Say 'Hello World'.

Analyzing the two preceding examples, you can see how Nashorn enables you to simplify Java code when you write a JavaFX application as a script:

There is no need to declare variable types, import packages, use annotations, specify the class name, and implement its main() method.

Only the JavaFX classes that are instantiated must be declared.

JavaBeans do not require the get and set prefixes, and are treated as JavaScript properties instead of as Java methods. For more information, see Using JavaBeans.

Implementing the javafx.event.EventHandler interface does not require you to specify the implemented method explicitly. Because handle() is the only method, Nashorn automatically applies the provided function to the method. For more information, see Extending Java Classes.

The JavaFX primary stage is available to Nashorn as a global property $STAGE. This global property enables you to treat the whole script as one start() function (you can still add the init() and stop() functions). Example 3-3 contains the source code for a simplified version of the JavaFX script application from Example 3-2.

Example 3-3 Simpler Version of the JavaFX Script Application (HelloWorldSimple.js)

In most cases, you should only add the classes that you instantiate or use to access static fields. However, for prototyping purposes, Nashorn predefines a set of scripts that can be loaded to import groups of JavaFX packages and classes. You can load a script using the load() function that takes a string with the name of the script. The following table lists the predefined script objects that are available for inclusion: