Update JLabel with countdown

1

I have a For that counts down, but when I pass the value to Label it only takes the last value of the loop.

This is my method:

public static void contagemRegressiva(){

        System.out.println("Start");
        int i=0;
        for( i=10;i>=0;i--){
            //label
           numero[0].setText(""+i);
        }

    }

The result of Label goes to 0 direct.

    
asked by anonymous 09.07.2015 / 05:07

2 answers

3

This is probably because the code runs so fast that you can only see the last value.

The ideal would be to set a timer to run every 1 second and then update the label.

You can see how to use the Timer class in this my other answer . Just add a command to update the label where the seconds are decremented.

    
09.07.2015 / 05:35
1

As @utluiz said this is because your code runs fast, the value is changing but you can not see this exchange because it is so fast ...

Insert this line of code:

Thread.sleep(1000); //faz com que o teu programa adormeça durante 1 segundo

attention: you must treat the exception in the possibility of being launched:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
    // handle the exception...        
    // For example consider calling Thread.currentThread().interrupt(); here.
}
    
09.07.2015 / 10:11