Search code examples
javaswingtimercountdown

CountDownTimer java equivalent


I am making an application where I use the Twitter API. I can reach the API limit after 180 API calls and what I want to do when I reach that limit is start a timer which is going to update a countdown (jLabel) every 1 seconds and the most important part is that the timer will finish after a certain X amount of seconds (taken from the API call).

Is there a desktop Java alternative for the Android CountDownTimer class?

I know I can do this but it doesn't seem proper:

time.scheduleAtFixedRate(new TimerTask() {
    long startTime = System.currentTimeMillis();
    @Override
    public void run() {
        if (System.currentTimeMillis() - startTime > X_SECONDS_HERE * 1000) {
            cancel();
        } else {
            // Update GUI countdown here
        }
}

Another alternative is to use a SwingWorker with a Thread.sleep(). Are these the only alternatives?


Solution

  • (As @AndrewThompson pointed out:) For Swing, you generally want to use a javax.swing.Timer instead of a java.util.Timer or TimerTask. The reason is that Swing is a single threaded framework, in which all update to the UI (in your case the label) should be made on the Event Dispatch Thread. With the Swing timer, the repetitive calls are made through an ActionListener, which acts on the EDT.

    The basic construct of the Timer is:

    Timer(int delay, ActionListener listener)
    

    where, delay is milliseconds for the initial and between-event delay, and the listener holds the callback functionality in the actionPerformed method. So you have something like

    Timer timer = new Timer(1000, new ActionListener(){
        private int count = 100;
    
        @Override
        public void actionPerformed(ActionEvent e) {
            if (count == 0) {
                ((Timer)e.getSource).stop();
            } else {
                // decrement the count and set the text for the label
            }
        }
    });
    // start the timer with a call to timer.start()
    

    With the code above, the call to actionPerformed will occur every 100o milliseconds. So whatever repetitive action you want to occur, put the code there.

    Resources: