2

I have a swing worker which configures a serial port connection. This process takes an indeterminable time to complete, sometimes 1 minute sometimes a lot more.

My problem arises when users click a button that needs configuration data whilst the worker thread is still configuring.

I would like to know how to execute a user's request only if the worker thread has completed. Else if worker thread in still alive, I want execution to wait until worker thread has finished.

Lai
  • 472
  • 6
  • 23
  • 1
    bind the button's action's enabled property to the (successful) termination of the worker, f.i. in a propertyChangeListener to the worker (as @mKorbel suggested) – kleopatra Oct 05 '12 at 11:05
  • I got round this problem differently, the button gets data from an external system so I had to put that within another thread in the actionPerformed(ActionEvent e) of the action listener. – Lai Oct 10 '12 at 09:00
  • glad you got it working :-) Whatever you did, be sure that you access all components/properties _only_ on the EDT. – kleopatra Oct 10 '12 at 09:04
  • the configuration was done on the [EDT](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html). This is a downside because it takes quite a long time to load the UI. I think I will have to live with that. It was just getting too complex for me. – Lai Oct 10 '12 at 10:10

2 Answers2

5
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 2
    +1 basically correct - next +10 would go for some example code (or a link to one of your examples :-) – kleopatra Oct 05 '12 at 11:06
2

You could check in your buttons ActionEvent if task.isDone() - where task is your SwingWorker - and continue only if it is true. But you might want to show a popup or something, otherwise the user might get confused why nothing is happening.

Another simple solution is to expose the button and disable it while the task is running and enable it again when it's finished. Then the user can't click the button until it's ready.

Sebastian_H
  • 349
  • 3
  • 13
  • Also consider allowing the button to cancel the worker, as shown [here](https://sites.google.com/site/drjohnbmatthews/randomdata). – trashgod Oct 05 '12 at 16:38