是有可能避免使用Swing的計時器來實現這一點,但如果你這樣做,那麼:
- 你必須確保環路和
Thread.sleep(...)
是在後臺運行的線程關閉的Swing事件線程。如果你不這樣做,你會凍結事件線程,從而凍結你的GUI並使其無用。
- 然後你必須確保當你只從後臺線程進行Swing調用時,你需要努力將這些調用放到Swing事件分派線程中。如果你不這樣做,你會冒着偶爾很難調試線程錯誤的風險。
由於涉及額外的工作和犯錯的風險,你會發現,這是多簡單和更安全,只需使用一個Swing計時器。例如,您的發佈代碼看起來很可能會讓整個GUI /應用程序進入睡眠狀態,因爲它有一個while循環和一個調用而不關心線程的Thread.sleep(...)
。
例如,如果沒有一個定時器,你的代碼可能看起來像(警告:代碼無法編譯,也不測試):
new Thread(new Runnable() {
public void run() {
int counter = 0;
while (counter < 10) {
lblDisplay.setText("Completed " + Integer.toString(counter));
try {
Thread.sleep(1000);
final int finalCounter = counter;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
lblDisplay.setText("Completed " + finalCounter);
}
});
} catch (InterruptedException ex) {
Logger.getLogger(Increment.class.getName()).log(Level.SEVERE, null, ex);
}
counter++;
}
}
}).start();
這是一個比較複雜一點比我喜歡,而搖擺定時器可能看起來像:
int delay = 1000;
new Timer(delay, new ActionListener() {
private int count = 0;
@Override
public void actionPerformed(ActionEvent e) {
if (count < 10) {
lblDisplay.setText("Completed " + counter);
} else {
((Timer) e.getSource()).stop(); // stop the Timer
}
counter++;
}
}).start();
比以前更簡單,更安全。
真正的問題是爲什麼?你的方法做得更好,然後Swing'Timer'? – MadProgrammer
請參閱編輯以回答。如有問題,請詢問。 –