# How do I fix a delay between the first and second KeyEvent

I recently got really interested in making my own little game. As I have no real game development background I'm still figuring stuff out, but I encountered a little problem.

While working on the user input, I noticed a delay between the first and the second time the key event gets called.

Can somebody give me a tip on how I can fix it? I already had a method to make the changing a bit slower. But the input delay kinda broke the method.

Here you can see the problem https://gfycat.com/EvenCreepyAsianconstablebutterfly

As you can see from the console output I have a delay before the second activation.

    run_anim = new Image[4];
try {
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

spriteInx = run_anim.length;

currentImage = sprite_idle;


Here is my key event:

public void keyPressed(KeyEvent e){
int key = e.getKeyCode();

for(int i = 0; i < handler.object.size(); i++){
Entity temp  = handler.object.get(i);

if(temp.getID() == ID.Player){
//Player Control
if(key == KeyEvent.VK_LEFT){
System.out.println(System.currentTimeMillis());
Player tempP = (Player) temp;
tempP.startRun("left");
}
if(key == KeyEvent.VK_RIGHT) temp.setVelX(2);
}
}
}


I add my images in the constructor of the player

And here you get the code for my startRun method.

public void startRun(String string) {
running = true;
if(string.equals("left")){
nextSprite(string);
}

}

public void nextSprite(String dir) {
if(running){
if(dir.equals("left")){
if(spriteCount < spriteInx-1){
currentImage = run_anim[spriteCount];
spriteCount++;
}else{
spriteCount = 0;
}

currentImage = run_anim[spriteCount];
setVelX(-2);
}
}
else{
currentImage = sprite_idle;
}
}


If you need anything further, just tell me.

I use AWT and Swing and nothing like lwjgl or jmonkeyengine.

• 1) we don't see the image, could you make sure you properly integrate it in the question? 2) please note that some delay is not modifiable depending on how the library you use is implemented: the OS can control how the "repeat key" event is sent to programs. May 17 '16 at 12:37

Instead of having the nextString method in the key event method, have it in a update method. Similar to the comment, it depends on the OS, so they won't always be the same. This might have sounded confusing, here's an example:

public void keyPressed(KeyEvent evt)
{
if(evt.getKeyCode() == KeyEvent.VK_LEFT)
{
player.runMotion = -1;
}
if(evt.getKeyCode() == KeyEvent.VK_RIGHT)
{
player.runMotion = 1;
}
}


Then in the player's update method, add the speed multiplied by the run motion to the player's velocity. Also, in the update method, run the next frame for the animation.