1

我有一个用 Netbeans 制作的应用程序,但我不知道如何Timer在 Java 中使用 a。Winform中有一个控制框,Timer只能拖拽使用。现在我想在about.setIcon(about4);执行(即 GIF)后使用 1 秒的计时器。

import javax.swing.ImageIcon;    
 int  a2 = 0, a3 = 1, a4 = 2;

 ImageIcon about2 = new ImageIcon(getClass().getResource("/2What-is-the-Game.gif")); 
  about2.getImage().flush();
  ImageIcon about3 = new ImageIcon(getClass().getResource("/3How-to-play.gif")); 
  about3.getImage().flush();
  ImageIcon about4 = new ImageIcon(getClass().getResource("/4About-end.gif")); 
  about4.getImage().flush();
  if(a2 == 0)
  {
      a2=1;
      a3=1;
  about.setIcon(about2);
  }
  else if (a3 == 1)
  {
      a3=0;
      a4=1;

      about.setIcon(about3);
  }
  else if (a4 == 1)
  {
      a4=0;
      a2=0;
      about.setIcon(about4);

  }
}   

我怎样才能做到这一点?

4

2 回答 2

1

在 Java 中,我们有几种实现 Timer 的方法,或者更确切地说是它的用途,其中一些是 -

  • 在执行任务之前设置特定的延迟量。
  • 找出两个特定事件之间的时间差。

Timer class provides facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.

 public class JavaReminder {
    Timer timer;

    public JavaReminder(int seconds) {
        timer = new Timer();  //At this line a new Thread will be created
        timer.schedule(new RemindTask(), seconds*1000); //delay in milliseconds
    }

    class RemindTask extends TimerTask {

        @Override
        public void run() {
            System.out.println("ReminderTask is completed by Java timer");
            timer.cancel(); //Not necessary because we call System.exit
            //System.exit(0); //Stops the AWT thread (and everything else)
        }
    }

    public static void main(String args[]) {
        System.out.println("Java timer is about to start");
        JavaReminder reminderBeep = new JavaReminder(5);
        System.out.println("Remindertask is scheduled with Java timer.");
    }
}

Read more from here:

于 2013-07-31T15:26:33.837 回答
0

在您的代码中声明一个实例java.util.Timer(在构造函数中?)并使用docs中的方法对其进行配置/控制。

import java.util.Timer;
import java.util.TimerTask;
...
private Timer t;
public class MyClass()
{
    t=new Timer(new TimerTask(){
        @Override
        public void run()
        {
           //Code to run when timer ticks.
        }
    },1000);//Run in 1000ms
}
于 2013-07-31T14:45:51.967 回答