Skip to main content

Asyncronous Update of UI elements

3 replies [Last post]
pjmlp
Offline
Joined: 2003-06-12

Hi everyone,

I'm doing a simple batch image processor in Swing using JDK 6

Now I have a problem. I want to present a progress dialog of the images that are being processed.

Now since the code that does the processing is invoked in the 'button pressed' event, the UI doesn't get shown properly.

So I thought, "no problem just use a SwingWorker", but that means interacting with the UI from the worker thread which also doesn't sound correct.

What should be the correct way to do the update?

I don't need an exact answer, some pointers to documentation would already be ok.

Thanks,
Paulo (a Swing newbie)

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
idk
Offline
Joined: 2005-01-12

Hi,

> So I thought, "no problem just use a SwingWorker", but that means interacting with the UI from the worker thread which also doesn't sound correct.

SwingWorker was introduced to make such communication easier.
You can batch process your images in SwingWorker.doInBackground, use SwingWorker.setProgress and "progress" PropertyChangeListener to track the process progress, use SwingWorker.publish and SwingWorker.process to process intermediate results (for example you can use it to display processed images as the batch process goes). SwingWorker's property change listeners and SwingWorker.process are invoked asynchronously on the 'Event Dispatch Thread' thus it is safe to access swing's components in them.

Please refer to the SwingWorker javadoc for the details:
http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html

Thanks,
Igor

pjmlp
Offline
Joined: 2003-06-12

Thanks for the feedback.

I'll have a look into it.

i30817
Offline
Joined: 2006-05-02

in your swingworker call SwingUtilities.invokeLater (for assynchronous updates) or SwingUtilities.invokeAndWait (for synchronous updates). Or if you only need to update in the end of the computation the swingworker should have a method that you can override that recieves the computed value returned in the computation function that runs on the original thread.