I have a Section and want to add a toolbar to it. I'm able to do it programmatically using the Actions but the requirement is to do it as much declaratively (in plugin.xml) as I can. So I'd like to define a Command and a Handler for each toolbar button but I don't know how to add them to the section's toolbar. Is there any way to do it declaratively in plugin.xml? If not, how can I do it programmatically?
Thanks!
I think you would have to write your own extension point to define what would go in the plugin.xml
and then write code to access the extension point registry to get the declared extensions and create the toolbar from the information.
See Eclipse Extension Points and Extensions for some more details.
You need to look at how to use org.eclipse.ui.menus extension
point. It supports adding commands/widgets to menu/popup/toolbar/trim.
//contributing to local toolbar
ToolBarManager localToolBarmanager = new ToolBarManager();
IMenuService menuService = (IMenuService) PlatformUI.getWorkbench().getService(IMenuService.class);
menuService.populateContributionManager(localToolBarmanager,
"toolbar:localtoolbar"); //id of your local toolbar
localToolBarmanager.createControl(control);
Here is a sample of how to create a toolbar for a section, make sure the toolbar is created before section.setClient()
.
protected void createToolbar(Section section) {
ToolBarManager toolBarManager = new ToolBarManager(SWT.FLAT);
toolBarManager.add(new Action("print") {
@Override
public void run() {
System.out.println("PRINT");
}
});
createSectionToolbar(section, toolBarManager);
}
/**
* create a toolbar in the passed section
*
* @param section
* @param toolBarManager
*/
protected void createSectionToolbar(Section section, ToolBarManager toolBarManager) {
Composite toolbarComposite = toolkit.createComposite(section);
toolbarComposite.setBackground(null);
toolBarManager.createControl(toolbarComposite);
section.clientVerticalSpacing = 0;
section.descriptionVerticalSpacing = 0;
section.setTextClient(toolbarComposite);
}
If you want to add declared commands from the plugin.xml
to the toolbar, have a look at CommandContributionItem
.
toolBarManager.add(new CommandContributionItem(new CommandContributionItemParameter(getSite(), "id", "commandId", SWT.NONE)));