在Java中,你不檢查是否有鍵被按下,而不是你聽到KeyEvent
秒。實(shí)現(xiàn)目標(biāo)的正確方法是注冊KeyEventDispatcher
并實(shí)現(xiàn)它以維護(hù)所需鍵的狀態(tài):
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.}
當(dāng)然,您可以使用相同的方法來實(shí)現(xiàn)isPressing("<some key>")
密鑰映射及其內(nèi)部包含的狀態(tài)IsKeyPressed
。