本文介绍了Java-没有GUI的倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我在制作基于文本的游戏(与其说是游戏,不如说是一种提高基本Java技能和逻辑的方法)。但是,我希望有一个计时器。它会根据我希望从变量到0的时间递减计数。现在,我已经看到了使用gui执行此操作的几种方法,但是,有没有gui / jframe等不执行此操作的方法。

Basically I am making a text based "game" (Not so much a game, more of a way to improve basic java skills and logic). However, as part of it I wish to have a timer. It would count down on the time I wish from the variable to 0. Now, I have seen a few ways to do this with a gui, however, is there a way to do this without a gui/jframe etc.

所以,我想知道的是。您可以不使用gui / jframe从x倒数到0吗?如果是这样,您将如何处理?

So, what I am wondering is. Can you make a count down from x to 0 without using a gui/jframe. If so, how would you go about this?

谢谢,一旦我有了一些想法,就会随着进展而编辑。

Thanks, once I have some ideas will edit with progress.

编辑

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

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

Above is how I am calling the thread/timer

public static void main(int count) {

如果我在TimerEg类中使用了此函数,则计时器将遵守。但是,在其他线程中编译main时。

If I then have this in the TimerEg class, the timer complies. However, when compiling the main in the other thread I get.

现在,我是否完全错过了对线程的理解,这将如何工作?还是我缺少什么?

Now, am I completely miss-understanding threads and how this would work? Or is there something I am missing?

错误:

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

推荐答案

与GUI相同,您将使用Timer ,但这里不是使用Swing Timer,而是使用java.util.Timer。请查看,细节。另外,请查看,

Same as with a GUI, you'd use a Timer, but here instead of using a Swing Timer, you'd use a java.util.Timer. Have a look at the Timer API for the details. Also have a look at the TimerTask API since you would use this in conjunction with your Timer.

例如:

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

}

这篇关于Java-没有GUI的倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 23:25
查看更多