[英]How to Stop Javax.Swing.timer?
我是Java新手,正在使用netbeans創建調度程序。 我的軟件將從用戶那里獲取時間和動作,並將這些數據輸入到單獨的數組列表中。 然后,我使用javax.swing.timer啟動了倒數計時器。 當用戶完成輸入數據並單擊“運行”按鈕時,計時器將從數組列表中的第一個元素獲取運行時間並開始遞減計數。 當倒數時間達到0時,計時器將從數組列表中的下一個元素獲取倒數時間,依此類推。
我的問題是,計時器運行完美,但是當arraylist中沒有更多元素時,它仍然不會停止。 請幫我解決一下這個。 這是我遇到麻煩的部分代碼:
private void btnstartRunActionPerformed(java.awt.event.ActionEvent evt) {
countdown = ActionTime.get(0);
Action.setText(ActionName.get(c));
timer = new Timer(1000,new ActionListener(){
@Override
public void actionPerformed(ActionEvent event){
if(countdown<=0){
try{
c++;
Action.setText(ActionName.get(c));
//this nested if statement is to check whether the array has any more elements.
//(This is the part that doesn't work.)
if(c >= ActionTime.size()){
timer.stop();
JOptionPane.showMessageDialog(null, "Workout Completed!");
}
countdown=ActionTime.get(c);
timer.restart();
} catch (Exception error2){
}
}
Time.setText(Integer.toString(countdown));
countdown--;
}
});
timer.start();
}
您應該更改:
c++;
Action.setText(ActionName.get(c)); //move this down
if(c>=ActionTime.size()){
timer.stop();
JOptionPane.showMessageDialog(null, "Workout Completed!");
}
至:
c++;
if(c>=ActionTime.size()){
timer.stop();
JOptionPane.showMessageDialog(null, "Workout Completed!");
return; //add this too as the program should not continue with below
}
Action.setText(ActionName.get(c)); //to here
因為當你試圖做ActionName.get(c)
時的值c
超過最大可能值時, get
方法將拋出Exception
。 這導致我們犯下第二個錯誤:
catch(Exception error2){
}
這樣做會使程序忽略Exception
並繼續執行,就好像什么都沒有發生。 一個容易犯的錯誤,使您誤以為其他事情是錯誤的,但是現在您知道了! 更改為:
catch(Exception error2){
error2.printStackTrace();
System.exit(-1); //or some error handling
}
或刪除try/catch
塊,以便Exception
將結束程序或以其他方式處理該Exception
。
這是給你的一個例子:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
public class Main extends JFrame {
Timer timer;
int counter;
Main(String title) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ActionListener a = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Counter = " + counter);
if (++counter > 10) {
timer.stop();
System.exit(0);
}
}
};
timer = new Timer(300, a);
timer.start();
pack();
setVisible(true);
}
public static void main(String[] args) {
new Main("Timer Demo1");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.