Search code examples
javaeventskeyboard

How do I handle simultaneous key presses in Java?


How do I handle simultaneous key presses in Java?

I'm trying to write a game and need to handle multiple keys presses at once.

When I'm holding a key (let's say to move forward) and then I hold another key (for example, to turn left), the new key is detected but the old pressed key isn't being detected anymore.


Solution

  • One way would be to keep track yourself of what keys are currently down.

    When you get a keyPressed event, add the new key to the list; when you get a keyReleased event, remove the key from the list.

    Then in your game loop, you can do actions based on what's in the list of keys.