KeyListener is not working in Java

点点圈 提交于 2019-12-12 05:32:11

问题


I want to be able to receive input from the keyboard by the user but I've added everything I thought would allow my program to do this and still it does not work. What am I doing wrong?

class KeyInput implements KeyListener {
    public void keyPressed(KeyEvent e) {
        System.out.println("keyPressed");
    }
    public void keyReleased(KeyEvent e) {
        System.out.println("keyReleased");
    }
    public void keyTyped(KeyEvent e) {
        System.out.println("keyTyped");
    }       
}

public GameView() {
    this.addKeyListener(new KeyInput());
}

The constructor works fine and KeyInput is an inner class of the GameView object. When running the game, if I press a key nothing gets printed to the system output. Am I missing something? Thanks!


回答1:


KeyListener is fickle mistress, it wants a lot of attention all the time. Basically, it will only raise key events if the component it is registered to has focus AND is focusable.

Generally, you want to avoid using it and use key bindings API instead, How to Use Key Bindings, but this will depend on whether you MUST use pure AWT APIs or not....



来源:https://stackoverflow.com/questions/27270284/keylistener-is-not-working-in-java

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