Susan Yanders
Susan Yanders

Reputation: 874

Java input stops working when window is unfocused

today I added keyboard input to my game the way I always do, with KeyListener, but for some reason, in my program whenever I click outside of the window and click back in, the key input just stops working. Here is what I have in my keyPressed and keyReleased methods:

public void keyPressed(KeyEvent e) {

    int code = e.getKeyCode();

    switch (code) {
    case KeyEvent.VK_W:
        keys[0] = true;
        break;
    case KeyEvent.VK_D:
        keys[1] = true;
        break;
    case KeyEvent.VK_S:
        keys[2] = true;
        break;
    case KeyEvent.VK_A:
        keys[3] = true;
        break;
    }
}

public void keyReleased(KeyEvent e) {

    int code = e.getKeyCode();

    switch (code) {
    case KeyEvent.VK_W:
        keys[0] = false;
        break;
    case KeyEvent.VK_D:
        keys[1] = false;
        break;
    case KeyEvent.VK_S:
        keys[2] = false;
        break;
    case KeyEvent.VK_A:
        keys[3] = false;
        break;
    }
}

Upvotes: 1

Views: 602

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347332

KeyListener is notorious for having focus issues. In order for a KeyListener to raise an event, the component it is registered to must not only be focusable, but must have focus.

Instead, you should be using Key Bindings which have mechanisms for overcoming these short comings

Amendment

If you're using AWT components you have another (few) problems. Essentially, you need to make the component focusable an when the use clicks on call requestFocusInWindow

Upvotes: 3

camickr
camickr

Reputation: 324207

Looks like you might be trying to do animation of a component with the keyboard. See Motion With the Keyboard which explains some problems with using the a KeyListener and shows how you might use Key Bindings.

Upvotes: 1

Related Questions