1

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;
    }
}
4

2 回答 2

3

KeyListener因注意力不集中而臭名昭著。为了让 aKeyListener引发事件,它注册到的组件不仅必须是可聚焦的,而且必须具有焦点。

相反,您应该使用具有克服这些缺点的机制的键绑定

修正案

如果您使用的是 AWT 组件,那么您还有另一个(很少)问题。本质上,当用户点击调用 requestFocusInWindow 时,您需要使组件具有焦点

于 2013-07-01T03:10:21.877 回答
1

看起来您可能正在尝试使用键盘对组件进行动画处理。请参阅Motion With the Keyboard,它解释了使用 KeyListener 的一些问题,并展示了如何使用 Key Bindings。

于 2013-07-01T03:12:37.110 回答