JavaFX: Best practice to implement glasspane-like mouse/touch event receiver which forwards events to underlying controls

StackOverflow https://stackoverflow.com/questions/18758803

  •  28-06-2022
  •  | 
  •  

Question

My challenge is following situation:

I want to add an invisible (opacity 0) pane over the whole application, which receives all mouse and touch events. When an event occurs it resets some kind of activity timer.

My first approach (without such pane) was adding listeners to the root pane, which worked pretty well. But... the buttons consume all events, so the timer does not get reset.

In my opinion, the glasspane solution would be a much more nicer solution, but I can't find a solution to forward received mouse and touch events to the underlying controls.

In short: the pane intercepts a mouse event (trigger to reset timer), and the underlying button gets clicked.

Any ideas please?

EDIT first solution I came to the solution to add an EventDispatcher to my root pane, which fires an custom event, when e.g. a mouse was pressed. So no glasspane, but it works:

    //this == myRootPane
    final EventDispatcher originalDispatcher = this.getEventDispatcher();

    EventDispatcher dispatcher = new EventDispatcher() {

        @Override
        public Event dispatchEvent(Event event, EventDispatchChain tail) {
            if(timeoutResetEventHdlr != null) {
                if(event instanceof MouseEvent) {
                    if(event.getEventType().equals(MouseEvent.MOUSE_PRESSED)) {
                        timeoutResetEventHdlr.handle(new PageTimeoutResetEvent());
                    }
                }

            }
            originalDispatcher.dispatchEvent(event, tail);
            return event;
        }
    };

    this.setEventDispatcher(dispatcher);
Was it helpful?

Solution

Don't use a glass pane or muck around with the event dispatcher, use an event filter on the scene.

Filters are triggered in the event capturing phase, rather than the event bubbling phase, so you can intercept the event and take some action on it before the underlying controls consume the event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top