6

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.

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.

Edit

// 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) {

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

Error

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

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

Found on line Runnable r = new TimerEg(gameLength);

Kyle93
  • 795
  • 5
  • 16
  • 26
  • Your TimerEg constructor call needs to have the same parameter count and types as is defined in the class's constructor. – Hovercraft Full Of Eels Sep 24 '12 at 16:28
  • @HovercraftFullOfEels unless I am mistaken they are. `static int gameLength = 0;` with the `public static void main(int count) {` being in the TimerEg class. Is this what you mean? – Kyle93 Sep 24 '12 at 16:32
  • The error says nothing about a static method but suggests that you're using a constructor incorrectly. That's about all I can say from your post. I am not seeing your code. – Hovercraft Full Of Eels Sep 24 '12 at 17:04

3 Answers3

9

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.

For example:

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

}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Just seen your edit, spent the last 20 mins trying to figure it out. Thanks for the example, I will look at it now! – Kyle93 Sep 23 '12 at 21:28
  • @Kyle: you're welcome. Also note that there are other ways to skin this cat. For instance, if your goal is to repeatedly create and execute threads on a regular schedule, look at using a [ScheduledThreadPoolExecutor](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html). – Hovercraft Full Of Eels Sep 23 '12 at 21:33
  • How would I pass the time I wanted it to run for to this? See my edit for what I mean. – Kyle93 Sep 24 '12 at 14:08
  • @Kyle: I can't see your images due to an internet firewall at work. – Hovercraft Full Of Eels Sep 24 '12 at 16:18
5

You could write your own countdown timer, as simply as:

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

Or you could use Java Timer API

Curious
  • 2,783
  • 3
  • 29
  • 45
  • Thanks, would this allow me to carry on doing other things or stop the program completely? – Kyle93 Sep 23 '12 at 21:29
  • Well to be able to carry on doing other things, you need to run the countdown timer in a separate thread. Please read a bit about threads. I can help if you still need assistance after that. – Curious Sep 23 '12 at 21:32
  • Alright, thanks I will take a look in to them once I have finished looking at Timers :) – Kyle93 Sep 23 '12 at 21:35
  • Would would you recommend reading about threads to help with this? Am I wrong in stating that I could have a thread with this running and a thread with my other code then once the timer is done that ends the thread and then would be able to trigger code in the other thread? Thanks – Kyle93 Sep 23 '12 at 21:50
  • yes, I would recommend reading about threads, at some point of time if not right now! :) And you are not wrong in what you have stated. – Curious Sep 23 '12 at 21:53
  • Thanks, thats a very interesting point. I will make sure I investigate more! I would look now, but I'm almost falling asleep haha. I'll take a good look tomorrow when words will stick. You got anything you would recommend reading? Thanks again – Kyle93 Sep 23 '12 at 21:58
  • You will find many articles on the internet, if you google, here is [one](http://www.javaworld.com/jw-04-1996/jw-04-threads.html). If you are interested in a good (& free) Java book (rather lengthy though), go [here](http://www.mindview.net/Books/TIJ/). – Curious Sep 24 '12 at 05:49
0

It is simple to countdown with 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();
Farukest
  • 1,498
  • 21
  • 39