All Things Techie With Huge, Unstructured, Intuitive Leaps

Exception in thread "Thread-0" org.eclipse.swt.SWTException: Invalid thread access



So you are getting your feet wet with Java SWT and you are having trouble updating your UI while you are doing some heavy processing.  Perhaps you have an intensive task like monitoring a stock quote and then updating the UI.  Either it plain doesn't work, or you keep getting the error:  Exception in thread "Thread-0" org.eclipse.swt.SWTException: Invalid thread access

Googling sometimes is not very helpful with this.

Obviously the way to work it, is to not put the intensive task in the main thread of the program.  That way you will never get an interrupt vector to update the UI.  So how do you do it?  I put the heavy duty processing task in a button, and kick a separate, non-UI thread to do the work.  Then at the point that you need to update the UI, kick a UI thread to do the update.  Here is a code snippet:

Button button1 = new Button(shell, SWT.PUSH);
button1.setBounds(220, third, 200, 50);
button1.setText("Do Work");
button1.addSelectionListener(new SelectionAdapter() {
 @Override
public void widgetSelected(SelectionEvent e) {
// Kick a thread that has nothing to do with the display
     Runnable runnable = new Runnable() {
         public void run() {
           for (int i = 0; i < 10; i++) {
             try {
               Thread.sleep(500);
             } catch (InterruptedException e) {
              
               e.printStackTrace();
             }

                      // this will print to the console, because the UI display thread is not involved
             System.out.println(i);

                      //Now get the UI thread to update the label 
                      display.asyncExec (new Runnable () {
                    public void run () {
                lblResultslabel.setText(i.toString());
               }
            });
           }
         }
       };
       new Thread(runnable).start();
  
 
}
});

Hope this helps someone.

No comments:

Post a Comment