Updating SWT periodically causes GUI to freeze

前端 未结 2 1708
孤城傲影
孤城傲影 2021-01-29 12:36

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 increment

相关标签:
2条回答
  • 2021-01-29 12:50

    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();
    
    0 讨论(0)
  • 2021-01-29 13:06

    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.

    0 讨论(0)
提交回复
热议问题