Thursday, October 12, 2006

 

Safer ways to parent your Shells

I have recently seen a fair amount of code where people are creating Dialogs parented off of the active shell using Display#getActiveShell().

There are a lot of shells in Eclipse. Beyond the obvious ones (the Workbench Window and any modal Dialogs you have open) you can have a Shell to animate trim, a Shell to show a tool tip, a Shell for content assist and so on. If one of these is the active shell you could parent your Shell off of all sorts of things.

To be safe try and use a Shell that you are aware of - i.e. if you are creating something off of another Dialog use the Shell of that Dialog. Of course this doesn't help you for your first Dialog which should use the Workbench Window as a parent.

If you look at ProgressManagerUtil#getNonModalShell() you can see how we do it for the Progress manager.


IWorkbenchWindow window =
PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window == null) {
IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
if (windows.length > 0)
return windows[0].getShell();
} else
return window.getShell();

return null;


you still need to handle the null case but it is not particularly common that you have no Workbench windows.

To be even safer in 3.1 org.eclipse.jface.ShellProvider was implemented. This can be used to parent any window and allows you to choose the Shell when the dialog is about to be created rather than when you create the instance.

This is really handy if you want to delay opening the dialog for some reason or are concerned about the shell you have selected closing on you.
Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?