Java Reference
In-Depth Information
Before moving on, it is useful to point out that ObservableList provides a method called
addAll( ) that can be used to add two or more children to the scene graph in a single call.
You will see an example of this shortly.
Using Buttons and Events
Although the program in the preceding section presents a simple example of using a
JavaFX control and constructing a scene graph, it does not show how to handle events.
Event handling is important because most GUI controls generate events that are handled by
your program. For example, buttons, check boxes, and lists all generate events when they
are used. In many ways, event handling in JavaFX is similar to event handling in Swing as
shown in the preceding chapter, but it's more streamlined. One commonly used control is
the button. This makes button events one of the most frequently handled. Therefore, a but-
ton is a good way to introduce event handling in JavaFX. For this reason, the fundamentals
of event handling and the button are described together.
Event Basics
The base class for JavaFX events is the Event class, which is packaged in javafx.event .
Event inherits java.util.EventObject , which means that JavaFX events share the same ba-
sic functionality as other Java events. Several subclasses of Event are defined. The one that
we will use here is ActionEvent . It encapsulates action events generated by a button.
In general, JavaFX uses what is, in essence, the delegation event model approach to
event handling. To handle an event, you must first register the handler that acts as a listener
for the event. When the event occurs, the listener is called. It must then respond to the event
and return. In this regard, JavaFX events are managed much like Swing events.
Events are handled by implementing the EventHandler interface, which is also in
javafx.event . It is a generic interface with the following form:
Interface EventHandler<T extends Event>
Here, T specifies the type of event that the handler will handle. It defines one method,
called handle( ) , which receives the event object as a parameter. It is shown here:
void handle(T eventObj )
In this case, eventObj is the event that was generated. Typically, event handlers are imple-
mented through anonymous inner classes or lambda expressions, but you can use stand-
alone classes for this purpose if it is more appropriate to your application (for example, if
one event handler will handle events from more than one source).
Search WWH ::




Custom Search