View RSS Feed

A JavaFX Blog

How to Filter JavaFX Events in a Scene Graph

Rate this Entry
by , 12-11-2016 at 06:45 PM (1413 Views)
JavaFX has a powerful event dispatch mechanism that allows different Node elements in a scene graph to intercept GUI events before and after they are delivered to their target node. Every time a new event is generated, an event dispatch chain is built for that event: this chain starts from the stage of the application window, continues with the scene displayed on that stage, and then follows the scene graph down to the target node of the event. For example, when a user clicks on a button in an application, a mouse click event is generated, whose target node is the button under the mouse cursor: the dispatch chain for this event goes from the stage of the application window to the button node, passing through the root node of the scene and any other (direct or indirect) parent nodes of the button in the scene graph.

Every element in an event dispatch chain has a chance of processing the event before it is delivered to its target. A special case of event processing is when the event is consumed: an event is consumed when its consume() method (defined in the Event class) is called; what’s special about consuming an event is that as soon as an event is consumed it stops traveling through its dispatch chain. So if an event is consumed before reaching its target, it will never reach its target.

The standard practice for processing an event in its dispatch chain before it reaches its target is by defining an event filter and registering the filter on an element of the chain: for example, to register an event filter on a Node object the following method is used:

Java Code:
<T extends Event> void addEventFilter(EventType<T> eventType, EventHandler<? super T> eventFilter)
When this method is called, the eventFilter object will receive all events of type eventType which travel through a dispatch chain to which the node belongs (unless of course an event is consumed before it reaches the node). The EventHandler<T> interface defines the handle(T event) method, which is called when an event reaches the node. For example, the following code snippet prevents mouse click events from reaching any node in a scene graph except the root node:

Java Code:
    new EventHandler<MouseEvent>() {
  public void handle(MouseEvent e) {
In the above example, as soon as a mouse click event reaches the root node, it is consumed by the event filter registered on the node, so any other nodes in the scene graph will not receive mouse clicks.

Submit "How to Filter JavaFX Events in a Scene Graph" to Facebook Submit "How to Filter JavaFX Events in a Scene Graph" to Digg Submit "How to Filter JavaFX Events in a Scene Graph" to Submit "How to Filter JavaFX Events in a Scene Graph" to StumbleUpon Submit "How to Filter JavaFX Events in a Scene Graph" to Google

Tags: None Add / Edit Tags
JavaFX Scene , JavaFX Events