user2328614
user2328614

Reputation:

Stopping swing Timer after it have executed one time

In a game that I'm making I have a power up that I only want to be visible for 10 seconds and then disapear. Therefor whenever you get the power up I run a swing Timer that have it's initial delay set to 10 seconds (10_000) and I have also set repeats to false so it should only run one time.

Whenever I first get the power up it will only be visible for 10 seconds as intended but when I get it again it will only be visible for a random amount of time (but never over 10 seconds) so therefor it seems like it does repeat itself. So how can I make it stop after it have runne one time when setRepeats(false); doesn't work?

This is the code for what happens when you get the power up.

if(!power.getPowerUp()){
 double xAirdrop = xSize - 500;
 double yAirdrop = ySize - 500;
 power.setX(Math.random() * xAirdrop + 64);
 power.setY(Math.random() * yAirdrop + 150);
 power.setPowerUp(true);
 Timer powerTimer = new Timer(10_000, new ActionListener(){
  public void actionPerformed(ActionEvent e){
   power.setPowerUp(false);  
   power.setWidth(power.getCrate().getWidth(null) + 250);
   power.setHeight(power.getCrate().getHeight(null) + 250);
  }
 });
 powerTimer.setInitialDelay(10_000);
 powerTimer.setRepeats(false);
 powerTimer.start();
}

Upvotes: 3

Views: 2354

Answers (1)

le3th4x0rbot
le3th4x0rbot

Reputation: 2451

The problem is that your timer is still running even though it is not firing events, therefore when you run start() it is somewhere in the middle of the cycle. This causes for it to run for a shorter time than 10 seconds. You need to run restart() instead of start() on subsequent runs. It might even work for the first run.

 powerTimer.setInitialDelay(10_000);
 powerTimer.setRepeats(false);
 powerTimer.restart();

From the javadoc:

restart() Restarts the Timer, canceling any pending firings and causing it to fire with its initial delay.

http://docs.oracle.com/javase/6/docs/api/javax/swing/Timer.html#restart()

Upvotes: 2

Related Questions