String tempNum="";
public void actionPerformed(ActionEvent event)
{
JButton src = (JButton) event.getSource();
if(src.equals(one))
{
if (pressed + 3000 > System.currentTimeMillis()) // user press > 3 seconds
{
tempNum = tempNum + "1";
//do a command
}
else //new
{
pressed = System.currentTimeMillis();
tempNum="";
tempNum = tempNum + "1";
//do a command
}
}
}
您好。在此程序中,用户将按JButton one
。用户在3秒内连续按one
并附加字符串" 1"到tempNum
。当用户在3秒后按下另一个one
时,tempNum
的值将为" 1"。
我的问题是:最初,当用户按下全新的" 1"时,如何检测用户是否处于非活动状态3秒钟?
例如:
输入:
用户输入:1
你怎么检测用户3秒后是否没有按任何东西?
答案 0 :(得分:0)
声明Long pressed = null;它的初始值将为null,这表示用户尚未按下按钮。
/**
* Declare pressed as Long pressed = null; in your code for the following to work as intended.
*/
StringBuilder tempNum = new StringBuilder();
String TO_ADD = "1";
int presses = 0 ;
int SECONDS = 3 ;
public void actionPerformed(ActionEvent event)
{
JButton src = (JButton) event.getSource();
/**
* Do call System.currentTimeMillis() once at the beginning and store it's value as later calls System.currentTimeMillis() could return later time.
*/
long pressTime = System.currentTimeMillis();
if(src.equals(one))
{
/**
* No press was done
*/
if (null == pressed)
{
pressed = pressTime;
}
if (pressed + SECONDS*1000 > pressTime) // user press > 3 seconds
{
presses++;
//do a command
}
else //new
{
pressed = pressTime;
presses = 1 ;
tempNum = new StringBuilder();
//do a command
}
tempNum.append(TO_ADD); //to get string call tempNum.toString(); in your code
}
}