Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm making a game Applet with Java that uses KeyListeners to control a paddle (for a game like Breakout/Pong). My basic implementation goes like this:

public void keyPressed(KeyEvent e) {
    switch (e.getKeyCode()) {
        case KeyEvent.VK_LEFT:
            direction = "LEFT";
        case KeyEvent.VK_RIGHT:
            //repeat for the rest
public void keyReleased(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT)
        direciton = "";//paddle doesn't move

My problem is that when the user tries to change the direction of the paddle twice too fast (let's say you press left, then right and left again super fast), the paddle freezes for a split second, and continues to move along its direction.

I understand that the problem is the logic in my code, but I can't think of a better implementation. What am I missing?

share|improve this question
up vote 1 down vote accepted

It needs state.

At the moment, this is what happens if you press Left, press Right, then release Left:

-> keyPressed(left):  direction = "LEFT";
-> keyPressed(right): direction = "RIGHT";
-> keyReleased(left): direction = "";

The paddle doesn't move, even though Right is still pressed!

You can solve this by checking in keyReleased if the opposite direction is still down and reset the direction to "" only if it isn't.

Unfortunately, since KeyListeners only tell you when keys go down and up, not whether they are down at the moment. You must track this state yourself. You can do it by setting variables leftIsDown and rightIsDown in the keyPressed and keyReleased cases for each key.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.