Search code examples
javatimekeypressmillisecondskeyrelease

How to know how many milliseconds Key is pressed in java


I want to find out the time in milliseconds that some key is pressed in java, but my result always prints a different number even though I pressed the key for less that one second or more. For Example If I pressed for less that one seconds shows 30, 45 or 98 and if I pressed for 3 seconds shows 35 , 50 , 120 I tried this code

long keyPressedMillis;
long keyPressLength;

.

public void keyPressed(KeyEvent arg0) {
    // TODO Auto-generated method stub
    int codigo = arg0.getKeyCode();
    if(codigo == KeyEvent.VK_SPACE)
    {
           keyPressedMillis = System.currentTimeMillis();           
    }
}

.

public void keyReleased(KeyEvent arg0) {
    // TODO Auto-generated method stub
    int codigo = arg0.getKeyCode();
    if(codigo == KeyEvent.VK_SPACE)
    {
           keyPressLength = System.currentTimeMillis() -keyPressedMillis;           
           System.out.println(keyPressLength);          
    }
}

Solution

  • keyPressed can (and will be) called repeatedly while the key is pushed. You should put in flag that you can check to see if this a repeated key event...

    int lastKey = -1;
    
    public void keyPressed(KeyEvent arg0) {
        // TODO Auto-generated method stub
        int codigo = arg0.getKeyCode();
        if (codigo != lastkey) {
            lastkey = codigo
            if(codigo == KeyEvent.VK_SPACE)
            {
               keyPressedMillis = System.currentTimeMillis();           
            }
        }
    }
    

    Of course, in your keyReleased event handler, you should reset this value so you don't end up missing a new key press ;)