Java Reference
In-Depth Information
«interface»
EventHandler<T extends Event>
Trigger an event
User
Action
source: SourceClass
+setOn XEventType (listener)
+ handle(event: T)
(2) Register by invoking
source.setOn XEventType (listener):
(1) A listener object is an
instance of a listener interface
listener: ListenerClass
(a) A generic source object with a generic event T
«interface»
EventHandler<ActionEvent>
source: javafx.scene.control.Button
+setOnAction(listener)
+handle(event: ActionEvent)
(2) Register by invoking
source.setOnAction(listener);
(1) An action event listener is an instance of
EventHandler<ActionEvent>
listener: CustomListenerClass
(b) A Button source object with an ActionEvent
F IGURE 15.5
A listener must be an instance of a listener interface and must be registered with a source object.
the handler class implements EventHandler<ActionEvent> in line 34. The source object
invokes setOnAction(handler) to register a handler, as follows:
Button btOK = new Button( "OK" ); // Line 16 in Listing 15.1
OKHandlerClass handler1 = new OKHandlerClass(); // Line 18 in Listing 15.1
btOK.setOnAction(handler1); // Line 19 in Listing 15.1
create source object
create handler object
register handler
When you click the button, the Button object fires an ActionEvent and passes it to invoke
the handler's handle(ActionEvent) method to handle the event. The event object contains
information pertinent to the event, which can be obtained using the methods. For example,
you can use e.getSource() to obtain the source object that fired the event.
We now write a program that uses two buttons to control the size of a circle, as shown
in Figure 15.6. We will develop this program incrementally. First, we write the program in
Listing 15.2 that displays the user interface with a circle in the center (lines 15-19) and two
buttons on the bottom (lines 21-27).
first version
F IGURE 15.6
The user clicks the Enlarge and Shrink buttons to enlarge and shrink the size
of the circle.
L ISTING 15.2
ControlCircleWithoutEventHandling.java
1 import javafx.application.Application;
2 import javafx.geometry.Pos;
3 import javafx.scene.Scene;
4 import javafx.scene.control.Button;
 
 
Search WWH ::




Custom Search