java - 如何使用定时器

标签 java timer

我有一个用 Netbeans 制作的应用程序,但我不知道如何在 Java 中使用 Timer。 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);

  }
}   

我怎样才能实现这个目标?

最佳答案

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

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

Timer类为线程提供了安排任务以便将来在后台线程中执行的工具。任务可以安排为一次性执行,也可以定期重复执行。

 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.");
    }
}

从这里阅读更多内容:

关于java - 如何使用定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17973524/

相关文章:

java - 在按钮中添加总计

java - 如何在 Worklight SOAP 适配器过程中传递 SOAP header 参数?

java - JDK版本问题

C# 相当于 Java 的 timer.scheduleAtFixedRate

java - 自动调用按钮

C++:析构函数级联期间的回调和系统计时器事件

java - 是否可以确定 zip 文件的 CRC?

java - 在 Java 中使用阻塞 NIO

python - “self”未定义 - 使用计时器进行线程处理

c - AVR编程如何激活16位定时器