簡體   English   中英

簡單的 Java 倒數計時器

[英]Simple Java countdown timer

我正在用 Java 做一個學校項目,需要弄清楚如何創建一個計時器。 我正在嘗試構建的計時器應該從 60 秒開始倒計時。

您可以使用:

 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
   }
 }

或類似的東西

編輯,我知道這不是最好的選擇,否則你應該創建一個新類:

執行此操作的正確方法:

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
           }
         }
    }

}

然后你在你的代碼中做: Thread thread = new Thread(MyTimer);

查看TimerActionListenerThread

有很多方法可以做到這一點。 考慮使用 sleep 函數並讓它在每次迭代之間休眠 1 秒並顯示剩余的秒數。

由於您沒有提供詳細信息,因此如果您不需要它完全准確,這將起作用。

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

用Java倒計時很簡單。 假設你想倒計時 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