Java Reference
In-Depth Information
Event Handling Using Scripting or Controller Properties
In the last section, we introduced you to using a method of the controller as an event handler for a node in an FXML
file. JavaFX allows two more ways to set up event handlers in FXML files. One way is to use scripting. Any JSR-223
compatible javax.script based scripting engine can be used. The language to be used for scripting must be
specified at the top of the FXML file. To use the Nashorn JavaScript engine that ships with Oracle JDK 8, the following
processing instruction must be present at the top of the FXML file:
<?language javascript?>
The fx:script element is used to introduce scripts. Both inline scripts and external file scripts are supported.
The following is an inline script:
<fx:script>
function actionHandler(event) {
webView.getEngine().load(address.getText());
}
</fx:script>
The external script takes the following form:
<fx:script source="myscript.js"/>
Any node in the FXML file that has an fx:id can be accessed from the scripting environment by their fx:id
names. If the FXML file has a controller, then the controller is available as a variable named controller . Variables
declared in fx:script sections are also available for use as variables in attributes in the rest of the FXML file. To use the
actionHandler(event) function defined in the fx:script section as an event handler, it can be specified as follows:
<TextField fx:id="address"
onAction="actionHandler(event)"
You can use either a function that takes no argument if your event handler does not need to inspect the
event object, or a function that takes one argument as the value of the event handler attribute, such as onAction . if you
call a function with one argument, then you must pass the system-provided event variable into it.
Caution
The ScriptingExample in Listings 3-29 and 3-30 illustrates event handling using scripting.
Listing 3-29. ScriptingExample.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?language javascript?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.HBox?>
 
 
Search WWH ::




Custom Search