SRL Archive - Java Help and Tutorials

Multiple keypresses


Macros

2009-03-02 12:00:38

Is there a way to process multiple key presses in java? I'm making a game, a side-scroller applet to be precise, and you move a little guy around with arrow keys. Only problem is, if you hold down the left key, (or right for that matter), and hit jump, it stops registering the the right or left movement, and jumps straight up.

I just thought of maybe having the program move right until the right arrow key is released, instead of just moving right when the right key is pressed, but there has to be an easier way >.< (And I don't know if that will work…)

Thanks, Dioxxipus

EDIT: Canceling the action only on a keyRelease, (instead of checking if the key is down every loop), works, (with a few minor kinks to work out, but still, it works)! I've been trying to get this working for quite some time now, and have searched Google a few times; all the posts I read say that it's either very hard or not possible…

I'm still looking for a different/easier way though, it seems like there must be one.

n3ss3s

2009-03-02 13:56:38

So what you want to do is hit space, and right after, while keeping space down, hit left or right?

If you haven't yet, check this: http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Robot.html


So just do keyPress for the spacebar, then wait (delay(int ms) in the Robot class), then keyPress for left or right, then keyRelease for left/right, then keyRelease for spacebar?

Macros

2009-03-02 14:02:20

First: This isn't automated, (just making sure, because you pointed me towards the Robot class).

Second: What I want to do is hold down the left, hit up and have the character move up and left simultaneously, (because left is held down the whole time). I accomplished this, (finally), by using keyRelease, so technically this problem is solved; but if anyone knows an easier way, without using keyRelease, it would be much appreciated!

Thanks-Dioxxipus

senrath

2009-03-02 14:32:06

How are you currently checking for keypresses?

Freddy1990

2009-03-02 15:02:42

Did you implement a keyboard listener?

Macros

2009-03-02 15:21:38

From: Freddy1990
Did you implement a keyboard listener?


Yup.

Also, if you click off the applet while holding down a key, the character continues to move, because it can't register the keyRelease. I think this is because I wrote, "addKeyListener( this );" what do I have to put in there, (instead of "this"), for it to "listen" to keys even when the applet doesn't have focus?

senrath

2009-03-02 15:27:01

You'd have to use JNI and some other language in order to listen to the keyboard when the applet doesn't have focus. Otherwise, in java, you have to have focus to listen to the keyboard and mouse.

Macros

2009-03-02 15:52:24

OK, I suppose that's all right, as I could just imitate a key release when the applet looses focus.

Thanks anyway peeps =p