简体   繁体   English

简单的 Java 倒数计时器

[英]Simple Java countdown timer

I'm working on a school project in Java and need to figure out how to create a timer.我正在用 Java 做一个学校项目,需要弄清楚如何创建一个计时器。 The timer I'm trying to build is supposed to count down from 60 seconds.我正在尝试构建的计时器应该从 60 秒开始倒计时。

You can use:您可以使用:

 int i = 60;
 while (i>0){
  System.out.println("Remaining: "i+" seconds");
  try {
    i--;
    Thread.sleep(1000L);    // 1000L = 1000ms = 1 second
   }
   catch (InterruptedException e) {
       //I don't think you need to do anything for your particular problem
   }
 }

Or something like that或类似的东西

EDIT, i Know this is not the best option, otherwise you should create a new class:编辑,我知道这不是最好的选择,否则你应该创建一个新类:

Correct way to do this:执行此操作的正确方法:

public class MyTimer implements java.lang.Runnable{

    @Override
    public void run() {
        this.runTimer();
    }

    public void runTimer(){
        int i = 60;
         while (i>0){
          System.out.println("Remaining: "+i+" seconds");
          try {
            i--;
            Thread.sleep(1000L);    // 1000L = 1000ms = 1 second
           }
           catch (InterruptedException e) {
               //I don't think you need to do anything for your particular problem
           }
         }
    }

}

Then you do in your code: Thread thread = new Thread(MyTimer);然后你在你的代码中做: Thread thread = new Thread(MyTimer);

查看TimerActionListenerThread

There are many ways to do this.有很多方法可以做到这一点。 Consider using a sleep function and have it sleep 1 second between each iteration and display the seconds left.考虑使用 sleep 函数并让它在每次迭代之间休眠 1 秒并显示剩余的秒数。

Since you didn't provide specifics, this would work if you don't need it to be perfectly accurate.由于您没有提供详细信息,因此如果您不需要它完全准确,这将起作用。

for (int seconds=60 ; seconds-- ; seconds >= 0)
{
    System.out.println(seconds);
    Thread.sleep(1000);
}

It is simple to countdown with Java.用Java倒计时很简单。 Lets say you want to countdown 10 min so Try this.假设你想倒计时 10 分钟,所以试试这个。

            int second=60,minute=10;
            int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
      second--;
      // put second and minute where you want, or print..
      if (second<0) {
          second=59;
          minute--; // countdown one minute.
          if (minute<0) {
              minute=9;
          }
      }
  }
};
new Timer(delay, taskPerformer).start();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM