Chapter 8 |
First event handler
In general, JavaFX uses a delegation event model approach to handle events. At first, we have to register the handler that acts as a listener for
the event. When an event occurs, the listener is called. The listener then responds to the event. Events are handled by implementing the EventHandler
interface.
The EventHandler<T>
interface contains the handle(T)
method for processing an event. The handler class must override this method to respond to the event. For example:
import javafx.event.ActionEvent; import javafx.event.EventHandler; class OKHandlerClass implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent e) { System.out.println("OK button clicked"); } }
The EventHandler
object must be registered with the event source object using the convenience method. (Many of the convenience methods are defined in the Node
class and are available to all of its subclasses.) The convenience methods for registering event handlers have the following format:
setOnEventtype(EventHandler<Eventclass> value)
Eventtype is the type of the event that the handler processes (e.g. setOnKeyTyped
for KEY_TYPED
events or setOnMouseClicked
for MOUSE_CLICKED
events). The event-class is the class that defines the event type (e.g. KeyEvent
for the events related to the keyboard input or MouseEvent
for the events related to the mouse input).
The following example displays a button in a pane. The code processes the ActionEvent
of the button. When we click the OK
button, the message “OK button clicked” is displayed.
import javafx.application.Application; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class HandleEvent extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { // Create a pane and set its properties HBox pane = new HBox(10); pane.setAlignment(Pos.CENTER); Button btOK = new Button("OK"); pane.getChildren().add(btOK); OKHandlerClass handler = new OKHandlerClass(); //create handler btOK.setOnAction(handler); //register handler // Create a scene and place it on the stage Scene scene = new Scene(pane); primaryStage.setTitle("HandleEvent"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
We now have seen a glimpse of the event-driven programming in JavaFX.
In addition to the convenience methods, we can also use a more general version of the handler registration. Namely, there are no convenience methods for all classes and types of the events. We can use the addEventHandler
method, whose arguments can be used to specify the event type and the handler. For example, the following line works similarly to the above (btOK.setOnAction(handler);
):
btOK.addEventHandler(ActionEvent.ANY, handler);
Try out
Try to run the program given above.
Used resources:
Chapter 8 |