All Things Techie With Huge, Unstructured, Intuitive Leaps
Showing posts with label SWT. Show all posts
Showing posts with label SWT. Show all posts

SWT Dialog To Front

I am working in org.eclipse.swt Java.  I create a dialog box.  The app was full screen and I didn't have any minimize corners on the screen.  I created a password dialog with code using the following:

PasswordDialog dialog = new PasswordDialog(new Shell());

When I ran the code, the main window was up front the the dialog was behind it. I knew this because the only way that I could see it, was with a task manager.

What to do?  I searched for a .toFront() method to no avail.  Finally I happened on the SWT.ON_TOP integer to use in the constructor, like this:

PasswordDialog dialog = new PasswordDialog(new Shell(SWT.ON_TOP));

Worked like a charm.  Hope this helps someone.

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.