Search code examples
javatimer

java timer for game


I have created a game in java and now I just need to add a timer that allow the user to play under 60s. I have searched on internet and found the timer for swing and util packages. could you please just give me a method to be able to use it in my game???


Solution

  • if you want something interactive you can use TimerTask and Timer classes:

    class ExpireTask extends TimerTask
    {
      YourClass callbackClass;
    
      ExpireTask(YourClass callbackClass)
      {
        this.callbackClass = callbackClass;
      }
    
      public void run()
      {
        callbackClass.timeExpired()
      }
    }
    

    So now you've got a timer that fires calling timeExpired of another class. Now with a Timer you can schedule it:

    ...
    Timer timer = new Timer();
    timer.schedule(new ExpireTask(callbackClass), 60000 /* 60 secs */);
    ...