0

I wrote a program to check for keypress, but all KeyEvents returned by the KeyEventDispatcher are null, even when I am pressing a key. I've tried implementing a NullPointerException Try-Catch but since all values are null if I do so nothing happens.

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

Just In case it is necessary: here is the code where I read k from 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;
    }
}

The problem seems to be the KeyboardFocusManager isn't working properly. Whereas normally ke should be a KeyEvent, the KeyboardFocusManager isn't sending the KeyEvents to the KeyEventDispatcher, so ke becomes null. I was wondering whether there were any alternatives to the KeyEventDispatcher that would also achieve what I want, or if there is another problem. Any help would be appreciated. Thanks!

UnsignedByte
  • 849
  • 10
  • 29
  • I can see a number of possible issues, but it would be guess work based on the out of context code snippets. Consider providing a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) – MadProgrammer May 15 '17 at 00:38
  • 1
    The other question which springs to mind is, in what ways does the key bindings API not solve the problem you're trying to solve? – MadProgrammer May 15 '17 at 00:46

0 Answers0