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");
}
答案 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
}
}