Reputation: 23
I need a timer for a game I am building and what it basically does is fire up an event that moves and object a square every second when I hit play. Now either I let the game take its course(the game finishes or the object moves out of bounds) or press play once again, the timer seems to be triggering the object to move faster than previously and so on, going faster and faster every time I restart the time.
private void playButtonMouseClicked(java.awt.event.MouseEvent evt) {
/*code*/
timer = new Timer(timerSpeed, new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
/*code that ends with something that calls timer.stop()*/
}
}
});
if(timer.isRunning()) //in case I don't let the game stop the timer
timer.stop();
timer.start();
}
I checked with timer.getDelay()
and the delay doesn't change, it stays the same, but I can see the arrow moving faster and faster every time. I'm using jPanels and a label with and icon to display the grid and the moving object.
Any ideas?
Upvotes: 2
Views: 1049
Reputation: 324118
but I can see the arrow moving faster and faster every time.
This tells me you have multiple Timers executing.
Your current code creates a new Timer every time the button is clicked.
The timer.isRunning()
check will never be true because you just created a new Timer which will not be running since you haven't started it yet.
So your old Timer may still be running but because you no longer have a reference to it, you can't stop it.
The solution:
Don't create a new Timer object every time you click the button. The Timer object should be created in the constructor of your class. Then you just start/stop the Timer as required
Upvotes: 6