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.

  1. In ExampleApp.java, import the Button class, then add an instance variable below hello:

    private Button button;
    

    In the constructor, add the following line immediately after the line that creates the Text object:

    this.button = new Button("Click me!");
    

    This creates a Button object; however, it will NOT automatically appear in the app's GUI.

  2. To add the Button object to the GUI, you need to add it to the scene. Here, we will add the button as a child of the HBox object that start uses as the root of the scene. In init, add the following line immediately after the line that adds the Text object to the HBox:

    this.root.getChildren().add(this.button);
    

    If you are adding multiple children to a node, you may prefer to use the variadic method addAll instead of add on the ObservableList<Node> object referenced by the result of getChildren.

  3. Compile ExampleApp.java, then rerun ExampleDriver. 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.

  4. 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 setOnAction method. Here is the signature of the setOnAction method:

    public final void setOnAction(EventHandler<ActionEvent> value)
    
  5. As you can see, to call the setOnAction method, we will need to supply a reference to an EventHandler<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 that EventHandler<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.

    1. Let's implement the EventHandler<ActionEvent> using a lambda expression. To do this, consult the API documentation for the interface and inspect its abstract handle method. The lambda expression will represent that method. Import the relevant types, then add the following lines in init, directly below the line that adds the button to root:

      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 prints you clicked me!.

    2. The previous step only created the EventHandler<ActionEvent> object. Now we need to register it with the button using the setOnAction method. Add the following line directly below the declaration you added in the previous step:

      this.button.setOnAction(buttonHandler);
      
  6. Compile ExampleApp.java, then rerun ExampleDriver. Click on the button. If you followed the steps correctly, then you should see a line beginning with handling event: followed by a line containing you clicked me! in your terminal window.

  7. 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 printf statement, so it does not print the handling 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!");
    
  8. 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 Text object in the scene graph. Replace the declaration of buttonHandler with 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, this has the same meaning as in the enclosing method, so it refers to the ExampleApp object. The hello variable is an instance variable, so it does not need to be final or effectively final. That restriction applies to local variables used from an enclosing method (see Using Caller-Supplied Behavior). Calling this.hello.setText changes the Text object that hello refers to; it does not assign a new value to hello.

    Alternative: Implementing EventHandler<ActionEvent> Without a Lambda

    As 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, this refers to the event handler object. We use ExampleApp.this to refer to the enclosing ExampleApp object and access its hello instance variable. You could also declare a separate named class that implements EventHandler<ActionEvent>. In that case, the class would need some other way to access the Text object, such as a constructor parameter.

  9. Compile ExampleApp.java, then rerun ExampleDriver. Click on the button. You should still see you clicked me! appear in your terminal window, and the text in the app should change from Hello, World!!! to Clicked!.

  10. 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:

  1. Did you register the handler? Creating the handler object is not enough. In our example, this.button.setOnAction(buttonHandler) connects it to the button.

  2. 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.

  3. 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.

  4. 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.

  5. 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.