Drop down menu from a toolbar button in JFace
January 19th, 2008I have been programming in SWT/JFace for some time now.
Today I needed a toolbar button that would display a popup menu when clicking the arrow next to the button. There are snippets around that show how to do this using plain SWT. After some experimentation I found how to do it in JFace. Actually, it is pretty easy. The JFace action is created with the Action.AS_DROP_DOWN_MENU style, and all you have to do is set the menu creator using
setMenuCreator (myMenuCreator);
myMenuCreator must be an instance of a class implementing the IMenuCreator interface.
My action, that should save the current file, giving the user the option to "save" or "save as..." in the popup menu, finally looked something like this:
-
protected class SaveConfigurationAction
-
{
-
protected MenuManager m_menu;
-
-
public SaveConfigurationAction ()
-
{
-
setImageDescriptor (imgDescriptorSave);
-
setToolTipText ("Save the current configuration");
-
setMenuCreator (this);
-
-
// create the manager for the drop down menu
-
m_menu = new MenuManager ();
-
{
-
@Override
-
public void run ()
-
{
-
save ();
-
}
-
});
-
-
{
-
@Override
-
public void run ()
-
{
-
saveAs ();
-
}
-
});
-
}
-
-
@Override
-
public void run ()
-
{
-
save ();
-
}
-
-
@Override
-
public void dispose ()
-
{
-
m_menu.dispose ();
-
}
-
-
@Override
-
{
-
return m_menu.createContextMenu (parent);
-
}
-
-
@Override
-
{
-
return null;
-
}
-
}