小编典典

Java如何检查用户是否按下了按键?

java

在Java中,我有一个程序需要连续检查用户是否按下了键。所以在伪代码中,像

if (isPressing("w"))
{
 //do somthing
}

提前致谢!


阅读 1370

收藏
2020-03-06

共1个答案

小编典典

在Java中,你不检查是否有键被按下,而不是你听到KeyEvent秒。实现目标的正确方法是注册一个KeyEventDispatcher,并实现它以维持所需密钥的状态:

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

public class IsKeyPressed {
    private static volatile boolean wPressed = false;
    public static boolean isWPressed() {
        synchronized (IsKeyPressed.class) {
            return wPressed;
        }
    }

    public static void main(String[] args) {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {

            @Override
            public boolean dispatchKeyEvent(KeyEvent ke) {
                synchronized (IsKeyPressed.class) {
                    switch (ke.getID()) {
                    case KeyEvent.KEY_PRESSED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = true;
                        }
                        break;

                    case KeyEvent.KEY_RELEASED:
                        if (ke.getKeyCode() == KeyEvent.VK_W) {
                            wPressed = false;
                        }
                        break;
                    }
                    return false;
                }
            }
        });
    }
}

然后,您可以随时使用:

if (IsKeyPressed.isWPressed()) {
    // do your thing.
}

当然,您可以使用相同的方法来实现isPressing("<some key>")键映射及其包裹在状态中的状态IsKeyPressed

2020-03-06