Stop windows Key Input Delay in Java

旧巷老猫 提交于 2019-12-11 20:59:45

问题


I am creating a side scrolling game and currently when I press an arrow key, the character moves, pauses then moves indefinitely until the key is released.

The pause comes from Windows configuration with Key Delay, so you don't accidentally type in duplicate key presses if you hold down the key too long.

I want to know if there is a way to get rid of this.

Here is my code for key presses:

public void keyReleased(KeyEvent ke){}

public void keyTyped(KeyEvent ke){}

public void keyPressed(KeyEvent ke){
    int code = ke.getKeyCode();

    if(code == KeyEvent.VK_UP){
        if(playerY > 0){
            playerY-=speed;
            repaint();
        }
    }

    else if(code == KeyEvent.VK_DOWN){
        if(playerY < 600){
            playerY+=speed;
            repaint();
        }
    }

    else if(code == KeyEvent.VK_RIGHT){
        if(playerX < 800){
            playerX+=speed;
            repaint();
        }
    }

    else if(code == KeyEvent.VK_LEFT){
        if(playerX > 0){
            playerX-=speed;
            System.out.println(playerX);
            repaint();
        }
    }
}

回答1:


When the key is pressed, you should set some variable by which you determine movement. On KeyReleased you unset this variable.

The way how you handle this it to call the method, for example moveLeft(), and in loop you are checking this variable. On KeyReleased, when you redefine it, the loop ends.



来源:https://stackoverflow.com/questions/23404863/stop-windows-key-input-delay-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!