javajface

JFace's MessageDialog fails in open() method


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();
  }
}

Solution

  • 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().