mow
mow

Reputation: 58

How to make count down timer in Java?

I want count down every second and update the label text?

int countdown = 100;

public void countingDown() {
    countdown = countdown - 1;
    label.setText(countdown + "second's left");
}

so how to run countingDown every second?

Upvotes: 2

Views: 8895

Answers (5)

Zaman Rajpoot
Zaman Rajpoot

Reputation: 523

control variable or you can set your on time(seconds)

int counter = 40;
 
    while(counter>0){
        try {
            Thread.sleep(1000);
            System.out.println(counter);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        counter--;
    }

Upvotes: 1

Zaman Rajpoot
Zaman Rajpoot

Reputation: 523

if you want to run on android use this

int Seconds = 11;
    void Start() {
        Seconds--;
        Log.i(TAG, "Start: "+ Seconds);;
        if(Seconds !=0){
            new Handler().postDelayed(this::Start, 1000);
        }
    }

it will work without affecting GUI

Upvotes: 0

Vy Do
Vy Do

Reputation: 52508

You maybe do like this:

package com.example;

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

public class MyTimer {

    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new App(), 0, 1000);
    }
}

class App extends TimerTask {

    int countdown = 100;

    public void run() {
        countdown = countdown - 1;
        System.out.println(countdown);
        //label.setText(countdown +"second's left");
    }

}

// Result:
//99
//98
//97
//96
//95
//94

It just works. Change System.out.println(countdown); by label.setText(countdown +"second's left"); as what you want.

Reference
http://docs.oracle.com/javase/8/docs/api/index.html?java/util/TimerTask.html
http://docs.oracle.com/javase/8/docs/api/index.html?java/util/Timer.html

Upvotes: 2

Vijendra Kumar Kulhade
Vijendra Kumar Kulhade

Reputation: 2255

You can use the below code

final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        final Runnable refresh = new Runnable() {
            public void run() {
                //countingDown stuff;
            }
        };
scheduler.scheduleAtFixedRate(refresh, 0, 1,SECONDS);

Upvotes: 0

Pradeep Charan
Pradeep Charan

Reputation: 683

Try this

int countdown=100;

    public void countingDown(){

     new Timer().schedule(new TimerTask(){

            @Override
            public void run() {
             countdown=countdown - 1;

                label.setText(countdown +"second's left");
            }   
        },0, 1000);
    }

Upvotes: -1

Related Questions