Java Reference
In-Depth Information
Introducing the Button Control
In JavaFX, the push button control is provided by the Button class, which is in
javafx.scene.control . Button inherits a fairly long list of base classes that include But-
tonBase , Labeled , Region , Control , Parent , and Node . If you examine the API docu-
mentation for Button , you will see that much of its functionality comes from its base
classes. Furthermore, it supports a wide array of options. However, here we will use its
default form. Buttons can contain text, graphics, or both. In this example, we will use text-
based buttons.
The Button constructor we will use is shown here:
Button(String str )
In this case, str is the message that is displayed in the button.
When a button is pressed, an ActionEvent is generated. ActionEvent is packaged in
javafx.event . You can register a listener for this event by calling setOnAction( ) on the
button. It has this general form:
final void setOnAction(EventHandler<ActionEvent> handler )
Here, handler is the handler being registered. As mentioned, often you will use an anonym-
ous inner class or lambda expression for the handler. The setOnAction( ) method sets the
property onAction , which stores a reference to the handler. As with all other Java event
handling, your handler must respond to the event as fast as possible and then return. If your
handler consumes too much time, it will noticeably slow down the application. For lengthy
operations, you must use a separate thread of execution.
Demonstrating Event Handling and the Button
The following program demonstrates event handling and the Button control. It uses two
buttons and a label. The buttons are called Up and Down. Each time a button is pressed, the
content of the label is set to display which button was pressed. Thus, it functions similarly
to the JButton example in the preceding chapter. You might find it interesting to compare
the code for each.
Search WWH ::




Custom Search