Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of Event consumes in JavaFX

I was trying to understand Event Handling in JavaFX and there I found this line.

The route can be modified as event filters and event handlers along the route process the event. Also, if an event filter or event handler consumes the event at any point, some nodes on the initial route might not receive the event.

Can you explain what is the meaning of event consumes?

like image 547
Asif Mushtaq Avatar asked Jun 14 '16 13:06

Asif Mushtaq


1 Answers

Events are passed along a specific route. In most cases (e.g. mouse/key events) The route will start at the root Node of the Scene and contain every Node on the path from the root Node to the target Node in the scene graph. On the route to the target Node, event filters are executed and if any of those filters should consume the event, this stops any further handling of the event. Once the event has reached the target Node if "travels" back to the root calling any event handler along the way. The event handling can be stopped there too by consuming the event.

Example:

@Override
public void start(Stage primaryStage) {
    Rectangle rect = new Rectangle(50, 50);

    StackPane root = new StackPane(rect);

    rect.addEventFilter(MouseEvent.MOUSE_CLICKED, evt -> {
        System.out.println("rect click(filter)");
//      evt.consume();
    });
    root.addEventFilter(MouseEvent.MOUSE_CLICKED, evt -> {
        System.out.println("root click(filter)");
//        evt.consume();
    });

    root.setOnMouseClicked(evt -> {
        System.out.println("root click(handler)");
//      evt.consume();
    });
    rect.setOnMouseClicked(evt -> {
        System.out.println("rect click(handler)");
//      evt.consume();
    });

    Scene scene = new Scene(root, 200, 200);

    primaryStage.setScene(scene);
    primaryStage.show();
}

If you click on rect, the event handling starts at the root Node. Here the filter is executed. If the event is not consumed in the filter, it is then passed to the rect Node, where the event filter receives the event. If that event is not consumed by the filter, the event handler of rect receives the event. If the event is not connsumed by that event handler, the event handler of the root Node receives the event.

Just uncomment some of the evt.consume() calls and see what happens...

like image 156
fabian Avatar answered Sep 21 '22 13:09

fabian