Swing's KeyListener and multiple keys pressed at the same time
Solution 1:
Use a collection to remember which keys are currently pressed and check to see if more than one key is pressed every time a key is pressed.
class MultiKeyPressListener implements KeyListener {
// Set of currently pressed keys
private final Set<Integer> pressedKeys = new HashSet<>();
@Override
public synchronized void keyPressed(KeyEvent e) {
pressed.add(e.getKeyCode());
Point offset = new Point();
if (!pressedKeys.isEmpty()) {
for (Iterator<Integer> it = pressedKeys.iterator(); it.hasNext();) {
switch (it.next()) {
case KeyEvent.VK_W:
case KeyEvent.VK_UP:
offset.y = -1;
break;
case KeyEvent.VK_A:
case KeyEvent.VK_LEFT:
offset.x = -1;
break;
case KeyEvent.VK_S:
case KeyEvent.VK_DOWN:
offset.y = 1;
break;
case KeyEvent.VK_D:
case KeyEvent.VK_RIGHT:
offset.x = 1;
break;
}
}
}
System.out.println(offset); // Do something with the offset.
}
@Override
public synchronized void keyReleased(KeyEvent e) {
pressedKeys.remove(e.getKeyCode());
}
@Override
public void keyTyped(KeyEvent e) { /* Not used */ }
}
Solution 2:
The KeyListener interface allows detecting key pressing and releasing separately. Therefore, you can maintain a set of "active keys", i.e. keys which have been pressed but not released yet.