KeyEventDispatcher KeyEvents始终为null

时间:2017-05-15 00:33:07

标签: java keyboard-events

我写了一个程序来检查按键,但是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应该是KeyEventKeyboardFocusManager不会将KeyEvents发送到KeyEventDispatcher,因此ke变为空。我想知道KeyEventDispatcher是否有任何替代方案可以实现我想要的,或者是否还有其他问题。任何帮助,将不胜感激。谢谢!

0 个答案:

没有答案