Update Jlabel with regressive count

Asked

Viewed 602 times

1

I have a For that makes a countdown, but when I will pass the value to the 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 straight to zero.

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 class Timer in this my other answer. Just add a command to update the label where seconds are down.

1

As @utluiz said this is because your code runs fast, the value is changing but you can’t see that change because it’s so fast...

Inserts this code line:

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.
}
  • 1

    You only need to pay attention to the use of 'Sleep' consented that it blocks the thread, so if there is no other thread the program stops responding. Depending on the GUI update speed the program may not yet display the updates, as with the pause it also does not have time to render the component. However it is possible to circumvent this by forcing the rendering of the component manually.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.