3

I have a JFace application and want to do some work on startup. So I overrode the open method of the window.
But now I have the problem that in the case of a failure I can't display an error message because the shell is null at this time. And I have no idea to solve this problem.

public class MyExample extends ApplicationWindow {
  public MyExample() {
    super(null);
  }

  public void run() {
    setBlockOnOpen(true);
    open();
    Display.getCurrent().dispose();
  }

  @Override
  public int open() {
    // do some work
    if (...) {
      MessageDialog.openError(getShell(), "Error", "Error occured");
    }
    return super.open();
  }
}
altralaser
  • 2,035
  • 5
  • 36
  • 55

1 Answers1

1

I would try:

Display.getDefault().syncExec(new Runnable() {

    @Override
    public void run() {
         MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error", "Message");
    }
});

EDIT:

The static method Display.getDefault() returns the default Display thread or a new one is created if it did not already exist.

On the other hand, the static method Display.getCurrent() returns the Display instance from the currently running thread, or null if the currently running thread is not a user-interface thread for any display.

See more on the Java Documentation of the Display class.

You may also want to take a look at the difference between syncExec() and asyncExec().

Community
  • 1
  • 1
DrKaoliN
  • 1,346
  • 4
  • 25
  • 39
  • 1
    Great it works! But can you explain the logic behind your solution? I understand that you move the MessageDialog to the UI thread but why the Shell exists then and there will be no error? And why you are using Display.getDefault and then Display.getCurrent? – altralaser Mar 10 '16 at 17:17
  • I have added details in my response. – DrKaoliN Mar 11 '16 at 08:45