带睡眠线程的java暂停秒表计时器?
我正在用Java制作秒表,但不知道如何暂停并继续计时。以下是我到目前为止所做的
startButton.addActionListener(this);
stopButton.addActionListener(this);
pauseButton.addActionListener(this);
public void actionPerformed(ActionEvent e) {
Calendar aCalendar = Calendar.getInstance();
if (e.getSource() == startButton){
start = aCalendar.getTimeInMillis();
startButton.setBackground(Color.GREEN);
stopButton.setBackground(null);
pauseButton.setBackground(null);
} else if (e.getSource() == stopButton) {
stopButton.setBackground(Color.RED);
startButton.setBackground(null);
pauseButton.setBackground(null);
aJLabel.setText("Elapsed time is: " +
(double) (aCalendar.getTimeInMillis() - start) / 1000 );
} else if (e.getSource() == pauseButton) {
pauseButton.setBackground(Color.YELLOW);
stopButton.setBackground(null);
startButton.setBackground(null);
}
}
如你所见,我只更改了暂停按钮的颜色。我真的不知道如何让用户点击按钮来暂停线程。我找到的所有关于线程的例子。sleep()是在特定的时间进行的
# 1 楼答案
你可以用秋千。计时器(不是util.Timer)如下所示:
您编写了一个名为
repeatingProccess()
的方法,它每隔interval
毫秒在自己的线程中反复工作。对于计时秒的时钟,您可以执行以下操作:注: 由于运行
seconds++
所需的时间,第二个时间不完全是1000毫秒,而是大约1001毫秒,但您也可以通过获取前后的系统时间并从时钟中减去差值来解决这一问题。为此,您应该使用日历API