在java中按下的键有多长

时间:2014-04-27 14:24:58

标签: java keyevent

好吧,我正在制作一个程序,它按键'f'按下3秒后应该做一些事情,如果它没有按下3秒然后它不应该做任何事情,我知道如何知道是否一个键被按下并释放但我找不到任何方法来知道按下的时间

private void formKeyPressed(java.awt.event.KeyEvent evt) {                                
    // to know if a key is being pressed

}
private void formKeyReleased(java.awt.event.KeyEvent evt) {                                
    // to know when a key is released

}  

修改 关于那些答案的Nevermid,它没有用。为了使它工作我必须这样做:

private long keyPressedMillis;
private boolean alreadyPassed==false;
...
private void formKeyPressed(KeyEvent event) {
if(alreadyPassed==false)
keyPressedMillis = System.currentTimeMillis()
alreadyPassed=true;
}
private void forKeyReleased(KeyEvent event) {
long keyPressLength = System.currentTimeMillis() - keyPressedMillis;
    alreadyPassed=false;
    System.out.println("Key Pressed "+keyPressLenght+" ms");

}

2 个答案:

答案 0 :(得分:0)

long whenTheKeyWasPressed;

private void formKeyPressed(java.awt.event.KeyEvent evt) {                                
    whenTheKeyWasPressed = System.currentTimeMillis();
}

private void formKeyReleased(java.awt.event.KeyEvent evt) {                                
    long now = System.currentTimeMillis();

    if ((now - whenTheKeyWasPressed) >= 3000L) {
        ...
    }
}  

但是,只有在释放密钥时才会触发操作。如果你想在时间达到3秒时触发动作,那么在keyPressed()方法中启动一个swing定时器,并从keyReleased()方法中停止它。

答案 1 :(得分:0)

您只需要跟踪按键的时间并计算释放时间。

long keyPressedMillis;

private void onKeyPressed(KeyEvent event) {
    keyPressedMillis = System.currentTimeMillis()
}

private void onKeyReleased(KeyEvent event) {
    long keyPressLength = System.currentTimeMillis() - keyPressedMillis;
    if (keyPressLength >= 3000) {
        //do whatever you need
    }
}