tags:

views:

82

answers:

3

How can I call a method every n seconds?

I want to do a slideshow with Swing and CardLayout and every n seconds it must show a different image calling a different method

+3  A: 
import java.util.*;

class MyTimer extends TimerTask
{
  public void run()
  {
    //change image
  }
}

then in your main you can schedule the task:

Timer t = new Timer();
t.schedule(new MyTimer(), 0, 5000);

first number is initial delay, second is the time between calls to run() of your TimerTask: 5000 is 5 seconds.

As BalusC noted usually you dispatch swing changes on AWT event thread. In this simple cause it shouldn't create problems when changing background from an outside thread, in any case you should use

public static void SwingUtilities.invokeLater(Runnable whatToExecute)

to dispatch your change on the right thread.

If you prefer BalusC approach just use an ActionListener:

public void BackgroundChange implements ActionListener
{
  public void actionPerformed(ActionEvent e)
  {
    //change bg
  }
}

javax.swing.Timer t = new javax.swing.Timer(5000, new BackgroundChange());

They both provide same functionality, but this later one is already prepared to work out together with Swing threads mantaining compatibility and avoiding strange synchronizations issues.

Jack
You're recommending `java.util.Timer`, not `javax.swing.Timer`.
BalusC
I used it many times for tasks similar to this one and it always worked.. by the way if you prefer the swing Timer you just modify the approach having a Swing style __ActionListener__ that implements your background change.
Jack
when swing, always use javax.swing.Timer
Xorty
It will "always" work when your Swing app "always" works. But when it ever unrecoverably crashes, the thread may still hang in the background and stall the JVM.
BalusC
+4  A: 

Since you're using Swing, you would like to use javax.swing.Timer for this. Here's a Sun tutorial on the subject.

BalusC
A: 

For any more than trivial animation in Swing app, check out Trident: http://kenai.com/projects/trident/pages/Home

ddimitrov