我想找出在java中按下某个键的时间(以毫秒为单位),但是我的结果总是会输出不同的数字,即使我按下的键少于一秒钟或更长时间。 例如如果我按下的时间少于一秒显示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);
}
}
答案 0 :(得分:3)
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
事件处理程序中,您应该重置此值,这样您就不会错过新的按键操作;)