I have two threads in an application. Thread A displays a form and
allows the user to interact with it, thread B executes a loop which
continually retrieves data and updates the form object by executing a
synchronized method in the form object.
I first tried to code thread A to use the showDialog() method on the form
object, then started thread a and then thread b. However, thread a
starts and the form then waits to be closed before the statement
starting thread b is executed. I then tried just using the show()
method in thread a - this allows the start of thread b to execute but
I lose my interaction with the form.
All AWT components need to be painted and have events delivered from
the same thread. Therefore, you should not call showDialog() or the
show method from different threads. This will produce unpredictable
behavior such as what you have descrbied. To ensure your actions on
AWT components occur synchronously within the main AWT thread, use the
javax.swing.SwingUtilities invokeAndWait() or invokeLater() methods.
Each one of these methods requires a Runnable argument that will be
executed within the AWT thread. invokeLater() will return
immediately, with the action being invoked when the AWT thread gets
around to it. invokeAndWait() will block and only return after the
AWT thread has executed the Runnable instance.