0

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.

MayNotBe
  • 2,110
  • 3
  • 32
  • 47

1 Answers1

0

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • So if I run it with `invokeLater(this)` what integer am I using to make the progress bar progress? Clearly I'm missing something. – MayNotBe Apr 27 '14 at 21:28
  • You would need to define a new instance of `Runnable` which was capable of updating the progress bar, to this end you would probably need to create a custom class which implements `Runnable` and took a `int` value via the constructor, then, in it's `run` method, update the progress bar accordingly. – MadProgrammer Apr 27 '14 at 21:54
  • Thanks for everything. I'm figuring all this out as I go. Using a SwingWorker now and I'm about to ask what I hope is a better question. – MayNotBe Apr 29 '14 at 16:48