简体   繁体   中英

Simple Java countdown timer

I'm working on a school project in Java and need to figure out how to create a timer. The timer I'm trying to build is supposed to count down from 60 seconds.

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);

查看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.

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. Lets say you want to countdown 10 min so Try this.

            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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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