Search code examples
javakeyswitch-statementkeyevent

Why are my Keyevents not working?


I am working on a game in Java which uses Keyevents. Basically, it is a template which I wanted to enhance but now I am struggling with some basic stuff. Here it goes:

In the keyPressed() method are a number of events, like this:

public void keyPressed(int key) {
    switch (key) {
    case KeyEvent.VK_A:
        System.out.println("A");
        methodA();
        break;
    case KeyEvent.VK_B:
        System.out.println("B");
        methodB();
        break;
    }
}

However, when I try to add another KeyEvent, like KeyEvent.VK_1 , it does not work/ the key is not recognized. Why is that? Am I missing something?


Solution

  • KeyListener has a well know issue. In order to receive key events, the component it is register to must be focusable and have focus. It is also possible for the key event to be consumed before it reaches your listener (by the component you are registered to).

    Instead, you should be Key Bindings, which will, give you greater flexibility in determining how key events are handled