Java - 没有GUI的倒数计时器

时间:2012-09-23 20:56:49

标签: java countdown

基本上我正在制作基于文本的“游戏”(不是游戏,更多是提高基本java技能和逻辑的方法)。但是,作为其中的一部分,我希望有一个计时器。它会减少我希望从变量到0的时间。现在,我已经看到了一些使用gui执行此操作的方法,但是,有没有办法在没有gui / jframe等的情况下执行此操作。

所以,我想知道的是。你可以在不使用gui / jframe的情况下从x到0进行倒计时。如果是这样,你会怎么做呢?

谢谢,一旦我有了一些想法就会进行编辑。

修改

// Start timer
Runnable r = new TimerEg(gameLength);
new Thread(r).start();

以上是我如何调用线程/计时器

public static void main(int count) {

如果我在TimerEg类中有这个,那么计时器符合。但是,在我得到的另一个线程中编译main时。

Error

现在,我完全错过了解线程以及它如何工作?或者有什么我想念的东西?

错误:

constructor TimerEg in class TimerEg cannot be applied to given types;
required: no arguments; found int; reason: actual and formal arguments differ in length

Runnable r = new TimerEg(gameLength);

行找到

3 个答案:

答案 0 :(得分:9)

与GUI相同,你使用的是Timer,但是这里使用的是java.util.Timer,而不是使用Swing Timer。有关详细信息,请查看Timer API。另请查看TimerTask API,因为您可以将它与计时器一起使用。

例如:

import java.util.Timer;
import java.util.TimerTask;

public class TimerEg {
   private static TimerTask myTask = null;
   public static void main(String[] args) {
      Timer timer = new Timer("My Timer", false);
      int count = 10;
      myTask = new MyTimerTask(count, new Runnable() {
         public void run() {
            System.exit(0);
         }
      });

      long delay = 1000L;
      timer.scheduleAtFixedRate(myTask, delay, delay);
   }
}

class MyTimerTask extends TimerTask {
   private int count;
   private Runnable doWhenDone;

   public MyTimerTask(int count, Runnable doWhenDone) {
      this.count = count;
      this.doWhenDone = doWhenDone;
   }

   @Override
   public void run() {
      count--;
      System.out.println("Count is: " + count);
      if (count == 0) {
         cancel();
         doWhenDone.run();
      }
   }

}

答案 1 :(得分:5)

您可以编写自己的倒数计时器,就像:

public class CountDown {
    //Counts down from x to 0 in approximately
    //(little more than) s * x seconds. 
    static void countDown(int x, int s) {
        while (x > 0 ) { 
            System.out.println("x = " + x); 
            try {
                Thread.sleep(s*1000);
            } catch (Exception e) {}
            x--;
        }   
    }

    public static void main(String[] args) {
        countDown(5, 1); 
    }   
}

或者您可以使用Java Timer API

答案 2 :(得分:0)

使用java进行倒计时很简单..

      int minute=10,second=60; // 10 min countdown
      int delay = 1000; //milliseconds
  ActionListener taskPerformer = new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
      second--;
      // do something with second and minute. put them where you want.
      if (second==0) {
          second=59;
          minute--;

          if (minute<0) {
              minute=9;
          }
      }
  }
};
new Timer(delay, taskPerformer).start();
相关问题