Java Platform, Standard Edition Nashorn User's Guide
Contents    Previous    Next

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

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:

jjs -fx JavaFXscript.js

For more information about jjs, see the tool's reference page at

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.

Example 3-2 contains the source code for a JavaFX script application that corresponds to the Java code in Example 3-1.

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:

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.

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:

This script ... Imports ...
fx:fxml.js javafx/fxml
fx:web.js javafx/scene/web
fx:media.js javafx/scene/media
fx:swing.js javafx/embed/swing
fx:swt.js javafx/embed/swt

Example 3-4 contains the source code of the simplified JavaFX script application from Example 3-3 with load() functions used to import the necessary packages and classes.

For more examples of JavaFX script applications, see Appendix A, "JavaFX Script Application Examples".

Contents    Previous    Next

Copyright © 1993, 2015, Oracle and/or its affiliates. All rights reserved.