3

I'm building a java program that downloads N elements from a server. I'd like to have a working progress bar, that shows "already downloaded elements"/N percentage. Right now, I update progressbar value by passing to the thread a reference to the GUI object, but it makes the code "ugly" ( GUI class creates the thread, that contains a reference to the GUI itself, creating a sort of loop). Is there a better way to do it?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
kaharas
  • 597
  • 2
  • 17
  • 39

4 Answers4

5

SwingWorker has some advantages in this context, as suggested in this example.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
2

Read the JProgressBar API and follow the link to the Swing tutorial on How to Use Progress Bars for a working example.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • 1
    @pst, The links are found in the API. You can't program if you don't have easy access to the API for reference. – camickr Jan 23 '11 at 03:38
2

In order to remove the "loop". Create a interface that the GUI extends that is passed to the working thread.

jzd
  • 23,473
  • 9
  • 54
  • 76
0

One design pattern that may be of use here is the listener pattern. Register a progress listener with the worker thread. The listener is then responsible for posting to the GUI (or whatever else may be interested in progress).

Because it in this sort of situation it is highly unlikely that you'd have multiple listeners, it's often better to just have a single listener (decreases complexity and overhead).

In my apps, long running operations are invoked by passing in a ProgressTracker (which has two event types: percentage and status text). This information is used to updated the JProgressBar, JLabel, whatever... I also use the ProgressTracker to check for whether the operation should be canceled.

SwingWorker does have some code that helps with merging multiple updates - but it is built around the assumption that long running tasks should inherit from SwingWorker, which doesn't help separation of concerns. It's really up to you which direction to head - I personally prefer the operations on my data to have nothing to do with GUI.

Remember to post your updates to any Swing components on the EDT using SwingUtilities.invokeLater()

Kevin Day
  • 16,067
  • 8
  • 44
  • 68