Pregunta

I am using eclipse if it would make any difference. I am trying to update a label 10 times at the press of a button, and I want it to wait between updates. I am trying to use thread.sleep in a for loop, but it does not update the label until the for loop reaches an end.

The code is close to. It also has much more code in it to specify what to change the label to.

for (int i = 0; i < 10; i++) {
    try{
        thread.sleep(250);
    }catch(InterruptedException ie) {
        return;
    }
    panel.repaint();
}

Thanks, it really helped!

¿Fue útil?

Solución

For the label to be updated, the main GUI event loop has to get its turn. But I'm guessing your code is running in the main thread, so the redrawing can't occur until your code is completely finished.

What you need to do is put your sleeping loop into a separate thread.

For this task, the SwingWorker class might be useful.

Otros consejos

Swing has a single thread (commonly called the Swing thread) and all button presses, redraws, processing, updates, etc happen in that thread.

This means that if you block that thread (such as for example by sleeping in a loop) then it cannot redraw the screen until you finish.

You need to farm out the work to another thread such as by using SwingWorker or user a Timer to schedule the updates. Swing has a Timer class you can use that is designed for exactly this case, just tell it to call you back every 250ms and make the change in that callback.

May be i am not getting your exact problem otherwise below is the solution:

for (int i = 0; i < 10; i++) {
    try{
   panel.repaint();
        thread.sleep(250);
// Or here if you want to wait for 250ms before first update
    }catch(InterruptedException ie) {
        return;
    }
}

Thoguh SwingWorker is better option. Move above logic to SwingWorker thread. Sample code is below:

   class Task extends SwingWorker<Void, Void> {
        @Override
        public Void doInBackground() {
           for (int i = 0; i < 10; i++) {
               try{
                   panel.repaint();
                   thread.sleep(250);
                 // Or here if you want to wait for 250ms before first update
                  }catch(InterruptedException ie) {
                  }
           }
          return null;
        }

    /*
     * Executed in event dispatching thread
     */
    @Override
    public void done() {
      // Do something if you want at the end of all updates like turn off the wait cursor

    }
 }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top