Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot listen to KeyEvent in JavaFX

I want my JavaFX program to respond to keyboard events.
I tried adding listeners to root Pane, to topmost Pane, but it doesn't respond to events!
Here is my code:

   AnchorPane root = new AnchorPane();
   root.setOnKeyPressed(new EventHandler<KeyEvent>() {

        @Override
        public void handle(KeyEvent t) {
            pressKey(t.getCharacter().charAt(0));
        }
    });
    root.setOnKeyReleased(new EventHandler<KeyEvent>() {

        @Override
        public void handle(KeyEvent t) {
            releaseKey(t.getCharacter().charAt(0));
        }
    });
    root.addEventHandler(EventType.ROOT, new EventHandler<Event>() {

        @Override
        public void handle(Event t) {
            if (t.getClass().equals(KeyEvent.class)) {
                System.out.println("AAARGH! " + ((KeyEvent)t).getCharacter());
            }
        }
    });

WHY U NO WORKING, key events? Am I doing something wrong here?
To be sure, mouse events works fine with the same code.

like image 947
Chechulin Avatar asked May 30 '13 11:05

Chechulin


1 Answers

One solution is to add an event listener to the scene. Because layouts don't have focus by default, so they don't respond on KeyEvents. KeyEvents are passed to the focused node first.

Another solution is to make your pane focusable:

root.setFocusTraversable(true)
like image 117
Alexander Kirov Avatar answered Sep 29 '22 12:09

Alexander Kirov