Swing KeyListener doesn't work when pressing Shift X Z and directions at the same time

My code:

addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent event) {
if (event.getKeyCode() >= KeyEvent.VK_LEFT && event.getKeyCode() <= KeyEvent.VK_DOWN)
direction.set(event.getKeyCode() - KeyEvent.VK_LEFT, true);
if (event.getKeyCode() == KeyEvent.VK_Z) direction.set(4, true);
if (event.getKeyCode() == KeyEvent.VK_CONTROL)          System.out.println(event.getKeyCode());
}

@Override
public void keyReleased(KeyEvent event) {
if (event.getKeyCode() >= KeyEvent.VK_LEFT && event.getKeyCode() <= KeyEvent.VK_DOWN) {
speed = event.isShiftDown() ? 1 : fastSpeed;
direction.set(event.getKeyCode() - KeyEvent.VK_LEFT, false);
}
if (event.getKeyCode() == KeyEvent.VK_Z) direction.set(4, false);
}

@Override
public void keyTyped(KeyEvent keyEvent) {
}
});


I start my application and press Shift, Z, and X at the same time, at this moment everything was fine (Successfully see command line output).
But when I press UP or DOWN, swing isn't invoking my listener (no command line output).

I've repeated many times and it's all the same.

Is there any work-arounds?

• Do you mean that the arrow keys don't work when Shift+Z+X are already pressed? This may be a hardware limitation of your keyboard.
– IMil
Dec 6, 2017 at 9:37
• Oh.... so is there an alternative workaround? Dec 6, 2017 at 10:15
• You can usually combo any/all modifier keys (shift, control, alt) in addition to at least one other key, so try seeing if this works if you move Z & X to other keys. Dec 6, 2017 at 12:50
• @ice1000 if you look at your keyboard you see that A, S, D, Z, X, Shift, Ctrl, Alt, Super are all located in a single corner of the keyboard. It is very likely that there's a physical limitation Dec 6, 2017 at 15:53
• I had the same exact problem. I just decided to use the keys not the arrows. I used it in this question Feb 1, 2018 at 1:58

1 Answer

From your recapitulation this might be an key rollover problem.

The term key rollover describes a tradeoff in keyboard design complexity for reduced production cost. Many standard keyboards have issues detecting more than three keys being pressed simultaneously.

As you are using Swing, that means you are using java. So in order to find out if it is a software or a hardware limitation you could try the following things:

• write a simple Swing application that only outputs the pressed keys and see if the input combo works
• write an even simpler AWT application, instead of using Swing, to really only output key-input to make some tests
• write a simple JavaFX application, instead of either AWT or Swing. JavaFX is the recommended replacement for Swing and if it is a software problem JavaFX is likely to have it fixed
• have a look at LWJGL and it's bindings to the GLFW library which provides an alternative way to get keyboard-inputs (this would allow you to find out if the Java standard libraries are the baddies...)