Java Reference
In-Depth Information
// Set the scene and title for the stage
stage.scene = new Scene(root);
stage.title = "Greeter";
// Show the stage
stage.show();
// A nested function to say hello based on the entered name
function sayHello(evt) {
var name = nameFld.getText();
if (name.trim().length() > 0) {
msg.text = "Hello " + name;
}
else {
msg.text = "Hello there";
}
}
}
The greeter application displays a window, as shown in Figure 11-4 . Enter a name
and press the Enter key or click the Say Hello button. A message with a greeting will be
displayed.
Figure 11-4. The greeter JavaFX aplication in action
Developing a JavaFX application is much easier in Nashorn. In the script, you
are able to call the getters and setters of Java objects using properties. You can access
properties directly for all Java objects, not just for JavaFX objects. For example, instead of
writing root.setSpacing(5) in Java, you can write root.spacing = 5 in Nashorn.
Adding the event handler for buttons is also easier. You can set an anonymous
function as the event handler for the buttons. Notice that you are able to use onAction
property to set the event handler rather than calling the setOnAction() method of the
Button class. The following snippet of code shows how to set the ActionEvent handler for
a button using a function reference sayHello :
// Add the event handler for the Say Hello button
sayHelloBtn.onAction = sayHello
 
Search WWH ::




Custom Search