开发者

call a method at a specified time

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 i开发者_运维问答mage calling a different method


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜