我想知道在java中按下某个键的时间(以毫秒为单位),但我的结果总是打印出不同的数字,即使我按下该键的时间少于一秒或更长。例如,如果我按不到1秒,显示30、45或98,如果我按3秒,显示35、50、120我试过这个代码
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);
}
}
keyPressed
可以(并且将)在按下键时被重复调用。你应该加入一个标志,你可以检查这是否一个重复的键事件…
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();
}
}
}
当然,在你的keyReleased
事件处理程序中,你应该重置这个值,这样你就不会错过一个新的按键;)