How do I handle simultaneous key presses in Java?
Asked Answered
S

4

19

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.

Stem answered 15/4, 2009 at 18:11 Comment(0)
W
21

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.

Wurster answered 15/4, 2009 at 18:30 Comment(6)
That doesn't seem that hackish. (Obviously there are slight problems related to focus - I guess assume all up on gain/lose focus.)Oppilate
@MichaelMyers how do you account for key repeated, if I hold down a key it goes like a pryamid on its side: a | a, a | a, a, a| a, a, a, a| a, a, a| a, a | aIncogitant
@JayAvon: I think that's worth asking a new question for.Wurster
@MichaelMyers #11851655 is the new question's link. Any help would be incredible.Incogitant
I suggest using a BitSet instead of a list of keysLoverly
This is just the answer I was looking for - I'm doing this in JOGL and on key press just sets a flat to true, on release sets it to false. Perfect, thank you!Mu
J
4

Here is a code sample illustrating how to perform an action when CTRL+Z is pressed:

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
class p4 extends Frame implements KeyListener
{
    int i=17;
    int j=90;
    boolean s1=false;
    boolean s2=false;

    public p4()
    {
        Frame f=new Frame("Pad");

        f.setSize(400,400);
        f.setLayout(null);
        Label l=new Label();
        l.setBounds(34,34,88,88);
        f.add(l);

        f.setVisible(true);
        f.addKeyListener(this);
    }

    public static void main(String arg[]){
        new p4();
    }

    public void keyReleased(KeyEvent e) {
        //System.out.println("re"+e.getKeyChar());

        if(i==e.getKeyCode())
        {
            s1=false;
        }

        if(j==e.getKeyCode())
        {
            s2=false;
        }
    }

    public void keyTyped(KeyEvent e) {
        //System.out.println("Ty");
    }

    /** Handle the key pressed event from the text field. */
    public void keyPressed(KeyEvent e) {
        System.out.println("pre"+e.getKeyCode());

        if(i==e.getKeyCode())
        {
            s1=true;
        }

        if(j==e.getKeyCode())
        {
            s2=true;
        }

        if(s1==true && s2==true)
        {
            System.out.println("EXIT NOW");
            System.exit(0);
        }
    }

    /** Handle the key released event from the text field. */

}
Jagir answered 18/1, 2011 at 12:25 Comment(1)
But what if other keys have to be non-modifier keys? Say like, directional keys for moving a sprite across the screen and space to shoot? You want to be able to shoot while movingArleenarlen
R
2

Generally speaking, what you are describing can be achieved using bitmasks.

Ringdove answered 15/4, 2009 at 18:33 Comment(1)
What do you mean Janusz? It's more than relevant. Yes, it's not Java related, but that doesn't mean its helpful.Nila
B
0

Oh, I had this problem too!

I tried making a simple Pong game following a tutorial I found.

But a lot of the time if I was holding one button and pressed another the new keypress would seem to register while the previous seemed to stop registering even if I was still holding the key pressed.

I thought that it was perhaps a limitation with the KeyListener feature so I tried rewriting my program to use Keybindings instead.

But if anything it made it all worse.

So I realized the problem was in the tutorial I was following. The way it handled the logic after listening to the keys.

So if you are experiencing this type of issues I'd recommend you to troubleshoot the code that you are working with!

Also take note that the behaviour of keys apparently can be different depending on your Operative system.

So in Windows when a key is pressed it will repeat like you know it will in a text editor. So when a key is pressed it will actually call repeatedly and then when you release it it will give you one release event.

So take note of that!

Also worth noting is that different keyboards will have different limitations on how many keys you can push simultaneously and that number will usually also be different depending on exactly the combination of keys that are being pressed.

Borszcz answered 12/2, 2023 at 17:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.