12.5. Events and Event HandlersΒΆ
In JavaFX, nodes can generate
Event
objects. This can happen automatically or in response to user input.
An event handler is an object with a method that is called to handle
an event when it is generated. A handler only runs if it has been
registered for that kind of event, and a node may have zero, one, or
many handlers registered for the same kind of event. Let's add a button
to ExampleApp, then register an event handler for one of the events
the button might generate.
In
ExampleApp.java, import the Button class, then add an instance variable belowhello:private Button button;
In the constructor, add the following line immediately after the line that creates the
Textobject:this.button = new Button("Click me!");
This creates a
Buttonobject; however, it will NOT automatically appear in the app's GUI.To add the
Buttonobject to the GUI, you need to add it to the scene. Here, we will add the button as a child of theHBoxobject thatstartuses as the root of the scene. Ininit, add the following line immediately after the line that adds theTextobject to theHBox:this.root.getChildren().add(this.button);
If you are adding multiple children to a node, you may prefer to use the variadic method
addAllinstead ofaddon theObservableList<Node>object referenced by the result ofgetChildren.Compile
ExampleApp.java, then rerunExampleDriver. You should now see the button.Move your mouse over the button. You should notice that the styling of the button changes automatically as your mouse cursor enters and leaves the visual area of the button (the change is subtle; look closely). Click on the button. Similarly, the styling of the button will change. As you interact with the button, you are actually causing the button to generate events. These events have default event handlers that cause the button's style to change.
When a user clicks on a button, that causes the button to generate an ActionEvent object. You can register an event handler for this event by calling the
setOnActionmethod. Here is the signature of thesetOnActionmethod:public final void setOnAction(EventHandler<ActionEvent> value)
As you can see, to call the
setOnActionmethod, we will need to supply a reference to anEventHandler<ActionEvent>object. It turns out that EventHandler<T extends Event> is an interface. This gives us many options. It also turns out that this interface is a functional interface, which means that we can use a lambda expression. We point out thatEventHandler<T extends Event>is an interface before mentioning lambda expressions to remind you that you can always implement the interface in the usual way instead of using a lambda expression. Let's create a handler that prints messages to standard output whenever the user clicks on the button.Let's implement the
EventHandler<ActionEvent>using a lambda expression. To do this, consult the API documentation for the interface and inspect its abstracthandlemethod. The lambda expression will represent that method. Import the relevant types, then add the following lines ininit, directly below the line that adds the button toroot:EventHandler<ActionEvent> buttonHandler = (ActionEvent event) -> { System.out.printf("handling event: %s\n", event); System.out.println("you clicked me!"); };
This lambda expression declares the parameter's type explicitly and uses a block body containing two statements. When the handler runs, the first statement prints
handling event:followed by a string representation of the event. The second statement printsyou clicked me!.The previous step only created the
EventHandler<ActionEvent>object. Now we need to register it with the button using thesetOnActionmethod. Add the following line directly below the declaration you added in the previous step:this.button.setOnAction(buttonHandler);
Compile
ExampleApp.java, then rerunExampleDriver. Click on the button. If you followed the steps correctly, then you should see a line beginning withhandling event:followed by a line containingyou clicked me!in your terminal window.If you only want the handler to print
you clicked me!, you can replace its declaration with this variant:EventHandler<ActionEvent> buttonHandler = (event) -> System.out.println("you clicked me!");
This variant omits the
printfstatement, so it does not print thehandling event:line when executed. It uses the shorter lambda syntax: the parameter type is inferred, and the body is a single method call instead of a block of statements.The line break after
=is optional. You can write the same declaration all on one line:EventHandler<ActionEvent> buttonHandler = (event) -> System.out.println("you clicked me!");
Our handler only prints to standard output; it does not change anything in the window. Let's change it so that it also changes the text displayed by the
Textobject in the scene graph. Replace the declaration ofbuttonHandlerwith the following lines:EventHandler<ActionEvent> buttonHandler = (event) -> { System.out.println("you clicked me!"); this.hello.setText("Clicked!"); };
This handler needs two statements, so we use a block body (see Shorter Lambda Syntax). The parameter type is still inferred.
Notice that the body of the lambda expression uses
this.hello. Inside a lambda,thishas the same meaning as in the enclosing method, so it refers to theExampleAppobject. Thehellovariable is an instance variable, so it does not need to befinalor effectively final. That restriction applies to local variables used from an enclosing method (see Using Caller-Supplied Behavior). Callingthis.hello.setTextchanges theTextobject thathellorefers to; it does not assign a new value tohello.Alternative: Implementing
EventHandler<ActionEvent>Without a LambdaAs we pointed out earlier,
EventHandler<T extends Event>is an interface, so you can implement it in the usual way instead of using a lambda expression. For example, the following code uses an anonymous class to create an object that behaves the same way as the object created using the lambda expression above:EventHandler<ActionEvent> buttonHandler = new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.out.println("you clicked me!"); ExampleApp.this.hello.setText("Clicked!"); } // handle };
Inside this anonymous class,
thisrefers to the event handler object. We useExampleApp.thisto refer to the enclosingExampleAppobject and access itshelloinstance variable. You could also declare a separate named class that implementsEventHandler<ActionEvent>. In that case, the class would need some other way to access theTextobject, such as a constructor parameter.Compile
ExampleApp.java, then rerunExampleDriver. Click on the button. You should still seeyou clicked me!appear in your terminal window, and the text in the app should change fromHello, World!!!toClicked!.Congratulations. You have successfully created your first interactive GUI app. Your event handler changes a node in the scene graph instead of merely printing a message to standard output. In Layout Panes, you will change how the nodes in the scene graph are laid out. Adding more nodes/components to the scene graph and registering event handlers that change them will be explored further in the class exercises and some of your projects.
My handler doesn't seem to do anything
If clicking the button does not produce the expected result, try the following checks:
Did you register the handler? Creating the handler object is not enough. In our example,
this.button.setOnAction(buttonHandler)connects it to the button.Are you working with the same button object? The variable used to register the handler should refer to the button that appears in the app. Look for a second
new Button(...)or a local variable that hides an instance variable with the same name.Is the button part of the displayed scene graph, visible, and enabled? Check where you added it to its parent. A button that is not visible might be missing from the scene graph, but it might also be hidden or outside the visible area.
What should the handler do? Our first handler only prints to the terminal; the revised handler also changes the text in the window. If your handler changes a node, make sure that node is the one displayed in the app. Changing a different node will not update the displayed one.
Did an exception occur? Check the terminal for a stack trace. An unhandled exception in an event handler is reported through the JavaFX Application Thread's uncaught exception handler; the window may remain open even though the handler did not finish.
The class containing this code does not need to extend Application.
We can create and register handlers in other classes, including custom
components that extend HBox or VBox.