Basic Controls
Controls are a special subset of Node
objects that were designed to handle user interaction. Most of them allow user input and support focus traversal.
Another difference from Shape
is that Control
objects are inherited not directly from Node
but through the Region
interface (like layout managers), which means their size and location are not fixed and can be managed by layout managers.
Button and Event Handlers
The first and most common control is button's family. Button
has an EventHandler
that is called when Button
is clicked (or fired). All code in the event handler is always run on JavaFX Application Thread:
// chapter2/other/ButtonDemo.java
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
In addition to text, you can use any Node
inside a button:
Button btn = new Button(); btn.setText("Say 'Hello...