0

I'm trying to track global key events, in particular arrow keys being pressed. For this, I'm attaching a handler to the currently active scene:

scene.setOnKeyPressed(event ->
        System.out.println("KEY PRESSED: " + event.getCode())
)

However, while most keys like letters, ctrl and tab are always detected, space and arrow keys only work while no element has focus. That is, as soo as I click anywhere in the window, some element gains focus and pressing space or arrows doesn't fire the event anymore. Through CSS styling I found out that once the scene has been clicked, there is always a focused element present, and above keys stop working in this case.

My guess is that focused nodes listen to key events and refuse to bubble them up if it's space or an arrow. My questions are:

  1. Why are those keys captured? I don't see a necessity for arbitrary UI components to always handle arrow and space key events.
  2. Can I prevent nodes from stealing key events, i.e. make them always bubble those? If not, is there another approach to detect key presses?
Cedric Reichenbach
  • 8,970
  • 6
  • 54
  • 89
  • 1
    You could just add an event filter to the scene, then you would capture the key press events before they are consumed by the scroll pane. – James_D Feb 10 '17 at 20:21

1 Answers1

1

It turns out that events were not captured by individually focused nodes, but a ScrollPane wrapping all of them. It captures those keys to scroll the viewport if necessary, and still doesn't bubble them if no scrolling is possible.

As explained in this answer, one could alter this behavior by using ScrollPane#addEventFilter, but should be careful to not affect usability in a negative way.

In that sense, it's probably better to leave arrow and space to their default behavior (scrolling) and switch to different keys.

Community
  • 1
  • 1
Cedric Reichenbach
  • 8,970
  • 6
  • 54
  • 89