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