Cannot listen to KeyEvent in JavaFX

爷,独闯天下 提交于 2019-12-18 16:08:46

问题


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.


回答1:


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)



回答2:


((KeyEvent)t).getCharacter() instead use ((KeyEvent)e).getText()




回答3:


also make sure you are importing the correct KeyEvent as in

import javafx.scene.input.KeyEvent;

rather than the KeyEvent from awt



来源:https://stackoverflow.com/questions/16834997/cannot-listen-to-keyevent-in-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!