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: , ,

Dec 22

The java.util.Timer class can be used to schedule code to be executed repeated at a fixed interval. The TimerTask class is used to encapsulate the code to be executed.


Timer timer = new Timer();
timer.schedule(new TimerTask()
{
    public void run()
    {
        // put the code you want to run here
    }
}, initialDelay, interval); 

written by objects \\ tags: , ,

Oct 08

Create a new Instance of Thread and call its start() method to start it.
You give the Thread constructor some instance that implements the Runnable interface. Once started the Thread will call the Runnable instances run() method is a separate thread.


Thread thread = new Thread(new Runnable()
{
   public void run()
   {
       // this will be run in a separate thread

       doSomething();
   }
});

// start the thread

thread.start(); 

written by objects \\ tags: