Java Reference
In-Depth Information
OKHandlerClass
is invoked to process the event. The object
handler2
is an instance
of
CancelHandlerClass
(line 20), which is registered with the button
btCancel
in line
21. When the
Cancel
button is clicked, the
handle(ActionEvent)
method (line 41) in
CancelHandlerClass
is invoked to process the event.
You now have seen a glimpse of event-driven programming in JavaFX. You prob-
ably have many questions, such as why a handler class is defined to implement the
EventHandler<ActionEvent>
. The following sections will give you all the answers.
An event is an object created from an event source. Firing an event means to create an
event and delegate the handler to handle the event.
Key
Point
When you run a Java GUI program, the program interacts with the user, and the events drive
its execution. This is called
event-driven programming.
An
event
can be defined as a signal
to the program that something has happened. Events are triggered by external user actions,
such as mouse movements, mouse clicks, and keystrokes. The program can choose to respond
to or ignore an event. The example in the preceding section gave you a taste of event-driven
programming.
The component that creates an event and fires it is called the
event source object
, or simply
source object
or
source component
. For example, a button is the source object for a button-
clicking action event. An event is an instance of an event class. The root class of the Java
event classes is
java.util.EventObject
. The root class of the JavaFX event classes is
javafx.event.Event
. The hierarchical relationships of some event classes are shown in
Figure 15.4.
event-driven programming
event
fire event
event source object
source object
ActionEvent
MouseEvent
EventObject
Event
InputEvent
KeyEvent
JavaFX event classes are in
the
javafx.event
package
WindowEvent
F
IGURE
15.4
An event in JavaFX is an object of the
javafx.event.Event
class.
An
event object
contains whatever properties are pertinent to the event. You can identify
the source object of an event using the
getSource()
instance method in the
EventObject
class. The subclasses of
EventObject
deal with specific types of events, such as action
events, window events, mouse events, and key events. The first three columns in Table 15.1
list some external user actions, source objects, and event types fired. For example, when click-
ing a button, the button creates and fires an
ActionEvent
, as indicated in the first line of this
table. Here, the button is an event source object, and an
ActionEvent
is the event object fired
by the source object, as shown in Figure 15.3.
event object
getSource()
Note
If a component can fire an event, any subclass of the component can fire the same type of
event. For example, every JavaFX shape, layout pane, and control can fire
MouseEvent
and
KeyEvent
since
Node
is the superclass for shapes, layout panes, and controls.
Search WWH ::
Custom Search