简体   繁体   中英

KeyListener is not working in Java

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!

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....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM