casgage
casgage

Reputation: 529

How to avoid org.eclipse.swt.SWTException: Invalid thread access

I have a listener to an SWT button which starts like this:

button1.addSelectionListener(new SelectionAdapter() {
  @Override
  public void widgetSelected(SelectionEvent e) {
    Runnable runnable = new Runnable() {
      public void run() {
        String nextValue = text1.getText();
        ...

I need the current value of the Text field called text1 in the UI, but the last line getText() fails with

org.eclipse.swt.SWTException: Invalid thread access

I know about syncExec/asyncExec (my code has several) but other threads here at StackOverflow suggest you only need to use it when you want to update a field in the UI. What is the correct way to read a UI field inside a listener?

Upvotes: 2

Views: 4726

Answers (1)

David G
David G

Reputation: 4014

Here are some code fragments that demonstrate how to run code synchronously & asynchronously (copied from Lars Vogel's VERY useful site).

// Update the user interface asynchronously
Display.getDefault().asyncExec(new Runnable() {
   public void run() {
    // ... do any work that updates the screen ...
   }
});

// Update the user interface synchronously

Display.getDefault().syncExec(new Runnable() {
   public void run() {
    // do any work that updates the screen ...
    // remember to check if the widget
    // still exists
    // might happen if the part was closed
   }
}); 

Upvotes: 2

Related Questions