0

I am trying to make a basic game in Java using a JFrame. For the game, I need to detect if several different keys are held down. I have this to add a KeyListener to the frame:

KeyListener keyListener = new KeyListener() {
    @Override
    public void keyTyped(KeyEvent e) {}

    @Override
    public void keyPressed(KeyEvent e) {
        KEYS.put(e.getKeyCode(), true);
    }

    @Override
    public void keyReleased(KeyEvent e) {
        KEYS.put(e.getKeyCode(), false);
    }
};
frame.addKeyListener(keyListener);

When I am just holding down one or two keys, it works fine. But if I press any more keys after that, it doesn't record it. I am currently using a KeyListener to get input, but I have had the same problems using an InputMap and an ActionMap. Why can Java sometimes only handle two keys being held at a time?

I already am storing when keys are held down in a HashMap so I can see if they are being held down. The problem is that the keyPressed method never gets called if two keys are already held down.

Scott
  • 591
  • 5
  • 9
  • `Why can Java only handle two keys being held at a time?` - this can be a problem with the keyboard. You can test out the `KeyboardAnimation` example found in [Motion Using the Keyboard](https://tips4java.wordpress.com/2013/06/09/motion-using-the-keyboard/). I can hold 3 keys down at the same time. I use JDK8 on Windows 7. – camickr Feb 19 '17 at 03:08
  • I have had this issue with multiple different keyboards on both Mac OS X and Windows – Scott Feb 19 '17 at 03:10
  • Each label can still only detect three inputs at a time, even in that example. – Scott Feb 19 '17 at 14:12
  • I managed to handle 6 keys at a time. I held down all four of the arrow keys and the icon didn't move. Then I was able to hold down 2 more of the "a, s, d, w" keys to get motion on the other icon. When I tried to press the 7th key it had no effect on the motion. So as suggested, I still believe it is related to the keyboard. – camickr Feb 19 '17 at 21:09
  • Question reopened. I don't believe it is a duplicate of: http://stackoverflow.com/questions/752999/how-do-i-handle-simultaneous-key-presses-in-java. This question states it can handle 2 keys at a time and is questioning why Java doesn't support more? I have handled up to 6 keys at a time. Not sure what a reasonable limit should be? – camickr Feb 19 '17 at 21:15
  • I've gotten six working, but it still is unreliable and sometimes three doesn't even work – Scott Feb 20 '17 at 01:46

0 Answers0