Updating SWT objects from another thread

Mridang Agarwalla picture Mridang Agarwalla · Dec 6, 2010 · Viewed 24.9k times · Source

In my Java application, when the main module is invoked, i start my SWT GUI in a separate thread. I need to perform some long opertations in the main thread and update the GUI thread. When I try to update the GUI thread from the main thread i.e. change a label text or something, i get a java.lang.NullPointerException. From what I've read online is because SWT doesn't allow non-UI threads to update UI objects. How can I update the GUI thread from the main thread.

I've found some examples online but they all deal with the scenario in which the GUI runs in the main thread and long operation is in separate thread. My scenario is the total opposite.

Could someone tell me how I can update widgets in the GUI thread?

Answer

Riduidel picture Riduidel · Dec 6, 2010

To say things short, SWT is a single-threaded UI toolkit. As a consequence, widgets must be updated in SWT event thread, like in Swing. Thus, you'll have to call the refresh using anonymous Runnable classes :

Display.getDefault().asyncExec(new Runnable() {
    public void run() {
        someSwtLabel.setText("Complete!");
    }
});

For a longer explanation, this JavaLobby article is a good introduction to this threading usage model.