-2

Problem: SWT freezes when GUI field is periodically updated.

I would like to have a SWT-based GUI with text field were values are periodically incremented.

  1. Initially I accessed textField from separate Thread what led to throwing exception:

Exception in thread "Thread-0" org.eclipse.swt.SWTException: Invalid thread access at org.eclipse.swt.SWT.error(SWT.java:4533) at org.eclipse.swt.SWT.error(SWT.java:4448) at org.eclipse.swt.SWT.error(SWT.java:4419) at org.eclipse.swt.widgets.Widget.error(Widget.java:482) at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:373) at org.eclipse.swt.widgets.Text.setText(Text.java:2311) at regreon.Incrementing.lambda$0(Incrementing.java:62) at java.lang.Thread.run(Thread.java:745)

  1. After reading SWT documentation (thanks to @marko-topolnik ) - I tried using display.SyncExec(Runnable r) or display.AsyncExec(Runnable r) with runnable that called Thread.sleep in the loop. But this caused the whole thing to freeze. Here is the code:

    package whatever; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.SWT;

    public class FreezingGUI {

    protected Shell shell;
    private Text text;
    
    public static void main(String[] args) {
        try {
            FreezingGUI window = new FreezingGUI();
            window.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void open() {
        Display display = Display.getDefault();
        createContents();
        shell.open();
        shell.layout();
    
        // HOW TO DO THAT???
        display.syncExec(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Integer i = Integer.parseInt(text.getText()) + 1;
                    text.setText(i.toString());
                }
            }
        }
        );
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }
    
    protected void createContents() {
        shell = new Shell();
        shell.setSize(450, 300);
        shell.setText("SWT Application");
    
        text = new Text(shell, SWT.BORDER);
        text.setEditable(false);
        text.setText("0");
        text.setBounds(30, 32, 78, 26);
    }
    

    }

How to avoid freezing and throwing exception?

Witold Kaczurba
  • 9,845
  • 3
  • 58
  • 67

2 Answers2

2

Any SWT operation which changes a UI object must be run on the SWT User Interface thread.

In your case the text.setText(i.toString()); line is an SWT UI operation and is running in a different thread.

You can use the asyncExec or syncExec methods of Display to run some code in the UI thread. So replace:

text.setText(i.toString());

with

final String newText = i.toString();
Display.getDefault().asyncExec(() -> text.setText(newText));

(this is assuming you are using Java 8).

Using asyncExec will do the UI update asynchronously. Use syncExec instead if you want to pause the thread until the update is done.

If you are using Java 7 or earlier use:

 final String newText = i.toString();
 Display.getDefault().asyncExec(new Runnable() {
    @Override
    public void run() {
      text.setText(newText);
    }
 });

Note you should also be checking for the Shell being disposed and stopping your background thread. If you don't do this you will get an error when you close the app. Your code incrementing i is also wrong. This thread works:

new Thread(() -> {
    for (int i = 1; true; i++) {
        try {
            Thread.sleep(1000);
        } catch (final InterruptedException e) {
            return;
        }

        if (shell.isDisposed())  // Stop thread when shell is closed
          break;

        final String newText = Integer.toString(i);
        Display.getDefault().asyncExec(() -> text.setText(newText));
    }
}).start();
greg-449
  • 109,219
  • 232
  • 102
  • 145
  • 1
    I wanted to add updates in the loop. I tried asyncExec and SyncExec. Both freeze when i add Thread.sleep(). – Witold Kaczurba Oct 26 '16 at 15:07
  • 1
    The Thread.sleep must **not** be in the `asyncExec` code, you must only have the `text.setText` method as I show. Putting the UI thread to sleep will cause the UI to freeze. – greg-449 Oct 26 '16 at 15:17
  • I updated the answer with the full code for the thread - this definitely works. – greg-449 Oct 26 '16 at 17:47
  • Checked and it works perfectly. Many thanks. For a newbie to SWT it is a bit new that you have to create Thread with Runnable that has another Runnable in it. – Witold Kaczurba Oct 26 '16 at 18:47
0

Looking at your code the reason your UI is freezing is because you are executing a runnable on Display.sync that never returns because of the while(true) loop, as a result, other UI threads don't get a chance to execute and the UI freezes. What you need to do is use Displasy.asyncRunnable and instead of having a runnable with while(true) make a scheduler or another thread that sleeps every x seconds that executes the runnable to make the update you want, this way the other UI threads can run preventing your UI from freezing.

Duncan Krebs
  • 3,366
  • 2
  • 33
  • 53