我是一个java新手,我正在使用netbeans创建一个调度程序。我的软件将从用户那里获得时间和动作,并输入这些数据来分离数组。然后我使用javax.swing.timer启动了一个倒计时器。当用户输入数据并按下"run“按钮时,定时器将从数组列表中的第一个元素获得运行时间并开始计数。当倒计时时间达到0时,计时器将从数组列表中的下一个元素获得计数下降时间,依此类推。
我的问题是,计时器运行完美,但是当数组中没有更多的元素时,它仍然不会停止。请帮我处理这个。下面是我的代码中我遇到麻烦的部分:
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();
}
发布于 2014-01-21 08:47:51
你应该改变:
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
结束您的程序或以其他方式处理。
发布于 2014-01-21 08:47:07
下面是一个给你的例子:
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");
}
}
https://stackoverflow.com/questions/21252960
复制相似问题