Documentation



JavaFX: Handling Events

2 Working with Convenience Methods

This topic describes convenience methods that you can use to register event handlers within your JavaFX application. Learn an easy way to create and register event handlers to respond to mouse events, keyboard events, action events, drag-and-drop events, window events, and others.

Some JavaFX classes define event handler properties, which provide a way to register event handlers. Setting an event handler property to a user-defined event handler automatically registers the handler to receive the corresponding event type. The setter methods for the event handler properties are convenience methods for registering event handlers.

Using Convenience Methods

Many of the convenience methods are defined in the Node class and are available to all of its subclasses. Other classes also contain convenience methods. Table 2-1 describes the events that convenience methods can be used to handle and identifies the classes in which the convenience methods are defined.

Table 2-1 Classes with Convenience Methods for Event Handling

User Action Event Type Class

Key on the keyboard is pressed.

KeyEvent

Node, Scene

Mouse is moved or a button on the mouse is pressed.

MouseEvent

Node, Scene

Full mouse press-drag-release action is performed.

MouseDragEvent

Node, Scene

Input from an alternate method for entering characters (typically for a foreign language) is generated, changed, removed, or committed.

InputMethodEvent

Node, Scene

Platform-supported drag and drop action is performed.

DragEvent

Node, Scene

Object is scrolled.

ScrollEvent

Node, Scene

Rotation gesture is performed on an object

RotateEvent

Node, Scene

Swipe gesture is performed on an object

SwipeEvent

Node, Scene

An object is touched

TouchEvent

Node, Scene

Zoom gesture is performed on an object

ZoomEvent

Node, Scene

Context menu is requested

ContextMenuEvent

Node, Scene

Button is pressed, combo box is shown or hidden, or a menu item is selected.

ActionEvent

ButtonBase, ComboBoxBase, ContextMenu, MenuItem, TextField

Item in a list, table, or tree is edited.

  • ListView.EditEvent

  • TableColumn.CellEditEvent

  • TreeView.EditEvent

  • ListView

  • TableColumn

  • TreeView

Media player encounters an error.

MediaErrorEvent

MediaView

Menu is either shown or hidden.

Event

Menu

Popup window is hidden.

Event

PopupWindow

Tab is selected or closed.

Event

Tab

Window is closed, shown, or hidden.

WindowEvent

Window


Convenience methods for registering event handlers have the following format:

setOnEvent-type(EventHandler<? super event-class> value)

Event-type is the type of 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 string <? super event-class> indicates that the method accepts an event handler for event-class or an event handler for one of its super classes as the argument. For example, an event handler for InputEvent could be used when the event is either a keyboard event or a mouse event.

The following statement shows the definition for the method that registers an event handler to handle the events that are generated when a key is typed, that is, when a key is pressed and released:

setOnKeyTyped(EventHandler<? super KeyEvent> value)

You can create and register your event handler in a single step by defining the handler as an anonymous class in the call to the convenience method. The event handler must implement the handle() method to provide the code needed to process the event.

A example of the use of a convenience method is shown in the code that is generated when you use the NetBeans IDE to create a JavaFX application. If you select the Create Application Class option when you create your JavaFX application, the main class that is created contains a "Hello World" application. The generated code is shown in Example 2-1.

Example 2-1 Hello World Example

package yourapplication;
 
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
 
public class YourApplication extends Application {
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Application.launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World");
        Group root = new Group();
        Scene scene = new Scene(root, 300, 250);
        Button btn = new Button();
        btn.setLayoutX(100);
        btn.setLayoutY(80);
        btn.setText("Hello World");
        btn.setOnAction(new EventHandler<ActionEvent>() {
 
            public void handle(ActionEvent event) {
                System.out.println("Hello World");
            }
        });
        root.getChildren().add(btn);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

The "Hello World" code creates a window with a single button. The setOnAction() method is used to register an event handler that handles the action events that are dispatched when the button is clicked. The handle() method in the event handler handles the event by printing the string "Hello World" to the console.

Examples for Mouse Events

Convenience methods for registering event handlers for mouse events include setOnMouseEntered, setOnMouseExited, and setOnMousePressed. Example 2-2 shows samples of these event handlers.

Example 2-2 Sample Event Handlers for Mouse Events

final Circle circle = new Circle(radius, Color.RED); 

circle.setOnMouseEntered(new EventHandler<MouseEvent>() {
    public void handle(MouseEvent me) {
        System.out.println("Mouse entered"); 
    }
});

circle.setOnMouseExited(new EventHandler<MouseEvent>() {
    public void handle(MouseEvent me) {
        System.out.println("Mouse exited");
    }
});

circle.setOnMousePressed(new EventHandler<MouseEvent>() {
    public void handle(MouseEvent me) {
        System.out.println("Mouse pressed");
    }
});

To see how similar event handlers are used, run the Ensemble sample, which is available in the JavaFX samples that can be downloaded from the JDK Demos and Samples section of the Java SE Downloads page. The Ensemble sample also provides the source code for the event handlers.

Examples for Keyboard Events

Convenience methods for registering event handlers for keyboard events include setOnKeyPressed and setOnKeyReleased. Example 2-3 shows samples of these event handlers.

Example 2-3 Sample Event Handlers for Keyboard Events

final TextField textBox = new TextField();
textBox.setPromptText("Write here");

textBox.setOnKeyPressed(new EventHandler<KeyEvent>() {
    public void handle(KeyEvent ke) {
        System.out.println("Key Pressed: " + ke.getText());
    }
});

textBox.setOnKeyReleased(new EventHandler<KeyEvent>() {
    public void handle(KeyEvent ke) {
        System.out.println("Key Released: " + ke.getText());
    }
});

To see how similar event handlers are used, run the Ensemble sample, which is available in the JavaFX samples that can be downloaded from the JDK Demos and Samples section of the Java SE Downloads page. The Ensemble sample also provides the source code for the event handlers.

Additional Resources

For information on the available convenience methods, see the JavaFX API documentation.

Close Window

Table of Contents

JavaFX: Handling Events

Expand | Collapse