Jan 25

Swing is single threaded so any updates need to be done from Swing’s event dispatch thread. If you need perform an update from another thread then you need to use the helper methods provided by the EventQueue class. The two methods are invokeLater() and invokeAndWait(), which queue the call for execution on the EDT. invokeLater() simpy queues it and returns, whereas invokeAndWait() will queue it and wait until it is executed before returning.

A common example we often get asked about is when the client has a thread that is receiving messages from the server and a message requires updating of the GUI. The following code outlines a very simple way for handling this situation by reading the message on one thread, and then passing it to the gui on the event dispatch thread.


final Message message = server.getMessage();

// pass message to the gui (on the event distpatch thread)

EventQueue.invokeAndWait(new Runnable() {
   public void run() {
      gui.receiveMessage(message);
   }
});

written by objects \\ tags: , ,