Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing's KeyListener and multiple keys pressed at the same time

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.

like image 921
Maksim Skurydzin Avatar asked Apr 12 '10 17:04

Maksim Skurydzin


People also ask

Which keys are pressed simultaneously?

switch between open programs or windows.

What is the purpose of KeyListener interface in event handling?

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.

How many methods are there in KeyListener in Java?

The KeyListener interface is found in java. awt. event package, and it has three methods.


2 Answers

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 */ }
}
like image 120
Ben S Avatar answered Oct 16 '22 17:10

Ben S


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.

like image 40
Eyal Schneider Avatar answered Oct 16 '22 16:10

Eyal Schneider