How to update SWT GUI from another thread in Java

Michał Ziober picture Michał Ziober · Aug 26, 2009 · Viewed 26.7k times · Source

I am writing a desktop application using SWT. What is the simplest way to update GUI controls from another thread?

Answer

McDowell picture McDowell · Aug 26, 2009

Use Display.asyncExec or Display.syncExec, depending on your needs.

For example, another thread might call this method to safely update a label:

  private static void doUpdate(final Display display, final Label target,
      final String value) {
    display.asyncExec(new Runnable() {
      @Override
      public void run() {
        if (!target.isDisposed()) {
          target.setText(value);
          target.getParent().layout();
        }
      }
    });
  }