How do I handle multiple key presses in a Java Applet?

I am teaching myself, from online tutorials, how to write games in Java. I am using Java Applets to create a Pong game. each paddle is controlled from different keys for 1v1 competition. this works fine if both users are hitting the keys at different times. but when one key is being held down and then another key is held down(ex: holding down on the arrow key, then user 2 holds the ‘S’ key), the second key overrides the first and the first paddle will stop moving. i’m guessing that i need to use threads but i don’t know much about them and i am having trouble understanding how to use/implement them. how would i go about handling the case when two (or more) keys are being held down?

Bonus: like i said i don’t know much about threads – i’m assuming i also need one for the ball/puck to be moving around while all else is going on. is the right and if so how do i put a thread on something that takes no input?

Thanks for you help, DJ

Answer

What you usually do is to remember the state of every keypress.

You keep an array of your actions(or an array of all the keys if you want too). A keyDown event results in e.g.

boolean actions[12];...
...

public boolean keyDown( Event e, int key ) {
 if (key == 'a') {
    actions[ACTION_LEFT] = true; 
  }
..
}

And you’ll need to catch the keyup event and set the actions to false when the keys are released.

In the movement logic you can just check the states of the keypresses

if(actions[ACTION_LEFT] == true)
   moveLeft();
if(actions[ACTION_RIGTH] == true)
   moveRight();

Leave a Reply

Your email address will not be published. Required fields are marked *