CMZS
CMZS

Reputation: 601

Eclipse PDE: Programmatically detect opened dialog and close it

On Eclipse Luna, I select a server and click the Start button on Servers view, then the server (for example Tomcat8) will get started. If something is wrong during the start-up process, a dialog will be populated to display the error messages (for example time-out). The dialog is modeless in this test case.

Now I need to start the server programmatically from a plugin. In case that errors occur, how could I programmatically detect that a dialog has been opened and how to close it?

Upvotes: 2

Views: 1076

Answers (1)

greg-449
greg-449

Reputation: 111142

You could use the Display.addFilter method to listen for all SWT.Activate events which will tell you about all Shells (and other things) being activated. You can then detect the shells you want to close.

Something like:

Display.getDefault().addFilter(SWT.Activate, new Listener()
  {
    @Override
    public void handleEvent(final Event event)
    {
      // Is this a Shell being activated?

      if (event.widget instanceof Shell)
       {
         final Shell shell = (Shell)event.widget;

         // Look at the shell title to see if it is the one we want

         if ("About".equals(shell.getText()))
          {
            // Close the shell after it has finished initializing

            Display.getDefault().asyncExec(new Runnable()
             {
               @Override
               public void run()
               {
                 shell.close();
               }
             });
          }
       }
    }
  });

which closes a dialog called 'About'.

In more recent versions of Java the above can be simplified to:

Display.getDefault().addFilter(SWT.Activate, event ->
  {
    // Is this a Shell being activated?

    if (event.widget instanceof Shell shell)
     {
       // Look at the shell title to see if it is the one we want

       if ("About".equals(shell.getText()))
        {
          // Close the shell after it has finished initializing

          Display.getDefault().asyncExec(shell::close);
        }
     }
  });

This uses Java 8 lambdas and method references and Java 16 instanceof type patterns.

Upvotes: 4

Related Questions