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.