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!