我制作了一个倒计时器,"停止"按钮应该停止倒计时并重置文本框。
class Count implements Runnable {
private Boolean timeToQuit=false;
public void run() {
while(!timeToQuit) {
int h = Integer.parseInt(tHrs.getText());
int m = Integer.parseInt(tMins.getText());
int s = Integer.parseInt(tSec.getText());
while( s>=0 ) {
try {
Thread.sleep(1000);
}
catch(InterruptedException ie){}
if(s == 0) {
m--;
s=60;
if(m == -1) {
h--;
m=59;
tHrs.setText(Integer.toString(h));
}
tMins.setText(Integer.toString(m));
}
s--;
tSec.setText(Integer.toString(s));
}
}
tHrs.setText("0");
tMins.setText("0");
tSec.setText("0");
}
public void stopRunning() {
timeToQuit = true;
}
}
当“停止”按钮被按下时,我调用stopRunning()
,但它不起作用。
另外,我是否正确地调用了stopRunning()
?
public void actionPerformed(ActionEvent ae)
{
Count cnt = new Count();
Thread t1 = new Thread(cnt);
Object source = ae.getSource();
if (source == bStart)
{
t1.start();
}
else if (source == bStop)
{
cnt.stopRunning();
}
}
interrupt()
的调用。如果轮询间隔超过两秒钟,我会添加对interrupt()
的调用。我的经验法则是:终端用户可以容忍不到一秒的延迟而不抱怨;超过一两秒的任何延迟都会让他们感到焦虑,而五秒钟的延迟会让他们点击重新加载按钮;-) - Sergey KalinichenkoCount
实例。创建一个Count
的单一实例,并在每次通过点击方法使用它。这里有一个修复方案在 pastebin 上:链接。 - Sergey Kalinichenko