Franz Payer
Franz Payer

Reputation: 4137

Fixing delay issue in java keypress action

I am creating a Java application that uses the keylistener. I have noticed that when using the keypressed listener when the user is holding down the key, it registers and then takes a second to detect the hold. Is there a way to get rid of this short delay?

public void keyPressed(KeyEvent arg0) 
{
    char key = arg0.getKeyChar();
    if(key == 'a')
        update = Status.Left;
    else if(key == 's')
        update = Status.Crouch;
    else if(key == 'd')
        update = Status.Right;
    else if(key == ' ')
        update = Status.Shoot;
    else
        update = Status.None;
    System.out.println(arg0.getKeyChar());
    this.repaint();
}

Upvotes: 1

Views: 1816

Answers (2)

Radu Simionescu
Radu Simionescu

Reputation: 4676

I suggest you don't detect the hold using the keyPressed event. Use a timer to constantly check for pressed keys. Use a BitSet. On keyPressed and on keyReleased update the BitSet to keep track of the pressed keys. This way you can detect multiple key presses at once. If you are building a game you already have the game clock which could be used for this

Upvotes: 1

Salil
Salil

Reputation: 536

I think these events are generated by the JVM / operating system. The user has to change the key-delay / key-repeat settings for eliminating the delay.

I don't think there is a way to control delay through code.

Upvotes: 1

Related Questions