Frage

I'm trying to learn about threads and JProgressBar.

I have a class that implements Runnable. Let's say that the run() just sleeps for 20 seconds and displays "Hello World".

Is it possible to create a JProgressBar that updates for as long as the thread is active?

If I had an int incrementer, could I do something like this (it doesn't work, obviously, but is there something along these lines?):

while (Thread.isAlive()) {
    incrementer++;

    progress.setValue(incrementer);
    Rectangle progressRect = progress.getBounds();
    progressRect.x = 0;
    progressRect.y = 0;
    progress.paintImmediately( progressRect ); 
}

Thanks for any help.

War es hilfreich?

Lösung

Yes, but you'll need to update the progress bar from the context of the thread, other wise you'll be blocking the a Event Dispatching Thread (EDT). This will mean you will need to synchronise the update with the EDT using something SwingUtilities.invokeLater.

Take a closer look at Concurrency in Swing for more details

You could also take a look at the indeterminate state of the progress bar, which can be used to indicate work in progress when you don't know how much work needs to be done

You could also use a SwingWorker which progress support via it's PropertyChange support

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top