在 Eclipse Luna 上,我选择一个服务器并单击“服务器” View 上的“启动”按钮,然后服务器(例如 Tomcat8)将启动。如果启动过程中出现问题,将会弹出一个对话框来显示错误消息(例如超时)。在此测试用例中,该对话框是无模式的。
现在我需要从插件以编程方式启动服务器。如果发生错误,我如何以编程方式检测对话框已打开以及如何关闭它?
最佳答案
您可以使用 Display.addFilter
方法来监听所有 SWT.Activate
事件,这些事件将告诉您有关所有 Shell(以及其他内容)被激活的信息。然后您可以检测要关闭的 shell。
类似于:
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();
}
});
}
}
}
});
这将关闭一个名为“关于”的对话框。
在最新版本的 Java 中,上述内容可以简化为:
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);
}
}
});
这使用 Java 8 lambda 和方法引用以及 Java 16 instanceof 类型模式。
关于Eclipse PDE : Programmatically detect opened dialog and close it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30334030/