简体   繁体   中英

Displaying a MessageBox when the SWT interface isn't running

I have a Java SWT application and i'm using this snippet of code to display a message box.

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

        @Override
        public void run() {
            try {

                MessageBox objError = new MessageBox(SysTray.shell, SWT.ICON_ERROR);
                objError.setMessage(strMessage);
                objError.open();
                SysTray.shell.getDisplay().dispose();
                System.exit(1);

            } catch (Exception e) {
                e.printStackTrace(); // Nothing to be handled here.
            }

        }

    });

This piece of code doesn't get executed when my SWT UI isn't created and therefore this block does not run. This has happened in situations where my UI thread has crashed.

How can I check if my UI is already created and if it isn't, I'd like to still show the message box to the user.

Thanks.

The first parameter of MessageBox is the surrounding shell.

You have to define a Display, and a Shell within the Display, to show the Message Box.

Display display = new Display();
Shell shell = new Shell(display);
// Define message box
shell.open();
while (!shell.isDisposed()) {
    if (display.readAndDispatch()) {
        display.sleep();
    }
}
display.dispose();

Edited to add and answer the comment:

To determine if a Display and Shell exist -

    Display display = Display.getCurrent();
    if (display != null) {
        Shell[] shells = display.getShells();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM