[英]Java Timer object error: Timer already cancelled
我有一個JButton,當按下它時會啟動一個倒數計時器。 當我按下按鈕時,它開始,然后再按一次(按鈕將顯示“停止”),則它停止。 但是,當我再次按下它以重新開始計時時,我收到一條錯誤消息:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Timer already cancelled.
這是我的代碼:
final static Timer t = new Timer();
static void startTimer(JButton b) {
t = new Timer(); // Solved: I needed to create a new Timer object.
t.scheduleAtFixedRate(new TimerTask() {
double timeleft = calcShutterSpeed;
@Override
public void run() {
String s = secondsToMinutes(timeleft);
time.setText(s);
timeleft--;
if (timeleft < 0) {
t.cancel();
b.setText("START TIMER");
b.setForeground(Color.BLACK);
}
}
}, 0, 1000);
}
static void stopTimer() {
t.cancel();
}
/**
* Creates the timer if "Start" is pressed.
*
* @param b
*/
static void timer(JButton b) {
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// If start button is pressed, change text to display stop
if (b.getText() == "START TIMER") {
startTimer(b);
b.setText("STOP TIMER");
b.setForeground(Color.RED);
}
// If stop button is pressed, cancel timer and change text to start
else if (b.getText() == "STOP TIMER") {
stopTimer();
b.setText("START TIMER");
b.setForeground(Color.BLACK);
}
}
});
}
可以解決此問題的任何提示或建議將不勝感激。 提前致謝!
編輯:對好奇心真的很簡單的修復。 該修復程序在代碼中。
我認為計時器上的“取消”方法仍然使計划任務處於取消狀態。 在取消之后直接調用“清除”方法應清除隊列並可能解決此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.