我写了一个程序来检查按键,但是KeyEvents
返回的所有KeyEventDispatcher
都是空的,即使我按了一个键。我已尝试实施NullPointerException
Try-Catch
但由于所有值均为null
,如果我这样做,则不会发生任何事情。
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent ke) {
synchronized (Processor.class) { //Processor is just the class this is in
k = ke;
return false;
}
}
});
以防万一有必要:以下是我从k
Processor
的代码
if (ke != null){
System.out.println(ke.getID());
switch (ke.getID()) {
case KeyEvent.KEY_PRESSED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = true;
}
if (ke.getKeyCode() == KeyEvent.VK_A) {
aPressed = true;
}
if (ke.getKeyCode() == KeyEvent.VK_S) {
sPressed = true;
}
if (ke.getKeyCode() == KeyEvent.VK_D) {
dPressed = true;
}
break;
case KeyEvent.KEY_RELEASED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = false;
}
if (ke.getKeyCode() == KeyEvent.VK_A) {
aPressed = false;
}
if (ke.getKeyCode() == KeyEvent.VK_S) {
sPressed = false;
}
if (ke.getKeyCode() == KeyEvent.VK_D) {
dPressed = false;
}
break;
}
}
问题似乎是KeyboardFocusManager
无法正常工作。通常ke
应该是KeyEvent
,KeyboardFocusManager
不会将KeyEvents
发送到KeyEventDispatcher
,因此ke
变为空。我想知道KeyEventDispatcher
是否有任何替代方案可以实现我想要的,或者是否还有其他问题。任何帮助,将不胜感激。谢谢!