1

I have a Graphics project that contains KeyListener, where the arrow keys and space bar controls the movement of a spaceship. However, when a key is held down, it registers the next key presses after a delay after the first. I would like for a held down key to register continuously.

I suspect that this is due to my computer's setting for key repeat delay, so is there any way to temporarily override this in my program, or a workaround for it?

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == 38) { //Up Arrow
        currentLevel.moveSpiffUp();
    } else if (e.getKeyCode() == 40) { //Down Arrow
        currentLevel.moveSpiffDown();
    } else if (e.getKeyCode() == 32 && !currentLevel.getFrapRayActive()) { 
        currentLevel.shoot();
    }
    repaint();
}
Marc Bacvanski
  • 1,458
  • 4
  • 17
  • 33
  • 1
    Use Key Bindings, and register both key press and key released as two separate bindings for each involved key. Then do the repetitive actions in a Swing Timer. – Hovercraft Full Of Eels Dec 06 '15 at 02:39
  • 1
    Essentially, you can't. Generally speaking, what you should be doing is, when the `keyPressed` occurs, you set a flag for the appropriate action, you use a game loop to update the state of you game based on the these flags. When `keyReleased` is called you reset the flag. Having said, I'd use the key bindings API instead, but the same principle applies – MadProgrammer Dec 06 '15 at 02:59
  • As an [example](http://stackoverflow.com/questions/11917377/do-something-once-the-key-is-held-and-repeat-when-its-released-and-repressed/11917604#11917604) – MadProgrammer Dec 06 '15 at 03:01

1 Answers1

0

I would suggest using key press and key released

public class MyKeyListener implements KeyListener {
    //class gets the input from the player
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if(KeyEvent.getKeyText(e.getKeyCode()).equals("Left")) {
            //left arrow key
        } else if (KeyEvent.getKeyText(e.getKeyCode()).equals("Right")) {
            //right arrow key
        }
    }
    public void keyReleased(KeyEvent e) {
        if(KeyEvent.getKeyText(e.getKeyCode()).equals("Left"){
            //left key released
        }
        if(KeyEvent.getKeyText(e.getKeyCode()).equals("Right")) {
            //right key released
        }

    }
}

I then used this bit of code in my main constructor

    main() {
        KeyListener listener = new MyKeyListener();
        addKeyListener(listener);
        setFocusable(true);
} 

This way you wont have your delay when hitting keys.

Ryan
  • 1,972
  • 2
  • 23
  • 36