Reputation: 13
I'm using a swing timer to get the x-position of a moving object every second for 10 seconds and save it in an array. Right now, the only way I can stop the repeat of the timer is using System.exit(0);. How do I stop the timer and continue executing the rest of the code?
int k=0;
{
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
for (int i=0;i<1;i++)
{
obj1pos[k]=x;
System.out.println(obj1pos[k]);
k+=1;
}
if (k>=10){
for (int i=0;i<10;i++){
System.out.print(obj1pos[i]+", ");}
System.exit(0);}
}
};
new Timer(delay, taskPerformer).start();
}
Upvotes: 1
Views: 276
Reputation: 38
You could make the timer accessible throughout the class by defining a private Timer at the top of your class;
private Timer timer;
Then define the timer as you do before by stating:
timer = new Timer(delay, taskPerformer).start();
And then in your if just call:
timer.stop();
Upvotes: 1
Reputation: 347332
The ActionEvent
will pass you the source
that generated the event, which, in this case, is the instance of the Timer
So you can just cast the ActionEvent#getSource
to a Timer
and call stop
on it when you need to...
if (k>=10){
for (int i=0;i<10;i++){
System.out.print(obj1pos[i]+", ");
}
System.exit(0);
((Timer)(evt.getSource())).stop();
}
Upvotes: 1