I'm a java newbie and I'm creating a scheduler program using netbeans. My software will get Time and action from the user and enter those data in to separate arraylists. I've then used javax.swing.timer to start a countdown timer. When user finished entering data and hit the "run" button,The timer will get the running time from the first element in the array list and start counting down. when the countdown time reach 0 , timer will get the count down time from the next element in the array list, and so on.
My problem is, the timer runs perfectly but when there is no more elements in the arraylist, it still won't stop. Please help me with this. Here's the part of my code I'm having trouble with:
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();
}
here is an example for you:
You should change:
to:
Because when you attempt to do
ActionName.get(c)
when the value ofc
exceeds the maximum possible value, theget
method will throw anException
. That leads us to the second mistake you're making:Doing this makes the program ignore the
Exception
and continue as though nothing happened. An easy-to-make mistake that deceived you into thinking something else is wrong, but now you know! Change it to:Or remove the
try/catch
block so that theException
will end your program or is handled some other way.