Session 9 |
First event handler
In general, JavaFX uses the delegation event model approach to handle the events. At first, we have to 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. Events are handled by implementing the EventHandler
interface.
The EventHandler<T>
interface contains the handle(T)
method for processing the 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.) Convenience methods for registering event handlers have the following format:
setOnEvent-type(EventHandler<event-class> value)
Event-type is the type of the event that the handler processes, for example, setOnKeyTyped
for KEY_TYPED
events or setOnMouseClicked
for MOUSE_CLICKED
events. event-class is the class that defines the event type, for example, KeyEvent
for events related to keyboard input or MouseEvent
for events related to mouse input.
The following example displays button in a pane. The code processes the ActionEvent
on 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:
Session 9 |