is there any conventional way in swing of tracking down the events, when two keyboard keys are pressed at the same time? I have a couple of ideas e.g. remembering the key and event generation time so that we could in a consecutive event handler invocation check the time difference between these two events and decide, whether it's a two-button event or not. But it looks like a kludge.
switch between open programs or windows.
Interface KeyListenerA keyboard event is generated when a key is pressed, released, or typed. The relevant method in the listener object is then invoked, and the KeyEvent is passed to it.
The KeyListener interface is found in java. awt. event package, and it has three methods.
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 */ }
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With