CS 4773 Object Oriented Systems Review of Swing And Threads


Threads and Java Using threads with Swing
  1. If an action takes a long time, fire up a thread to handle it
  2. If an action can block on input or output, fire up a new thread to handle it.
  3. If you need to wait for a specific amount of time, don't sleep in the event dispatch thread, use a timer event.
  4. The work done in the worker threads cannot touch the user interface.
The last of these rules is called the single thread rule for Swing programming.

Exception to the single thread rule:

How to update from the event dispatch queue: Use one of the static methods in the EventQueue class:
invokeLater(Runnable runnable) or
invokeAndWait(Runnbale runnable) throws InterruptedException, InvocationTargetException
Example:
EventQueue.invokeLater(new Runnable()
                      {
                         public void run() {
                            label.setText("This is a label");
                         }
                      });
See the SwingThreadTest example.
Some modifications made form the Core Java code: