Programmatic command contributions

Have you ever faced the task of programmatically adding commands to a given menu? It is not that difficult – when you finally found out ;).
First of all, you need a target menu, whether it is declared or programmatically created does not matter. What you actually need is the menu’s location URI. You may the create an AbstractContributionFactory with the menu’s location URI:

AbstractContributionFactory contribFactory = new AbstractContributionFactory ("", null) {
public void createContributionItems(IServiceLocator locator, IContributionRoot additions) {
// add the contribution using it's source
additions.addContributionItem(createContributionItem(contribSource), null);
IMenuService menuService = (IMenuService)getViewSite().getService(IMenuService.class);
menuService.addContributionFactory(locator, contribFactory);

The items are added to the IContributionRoot within the factory’s createContributionItems() method. The factory is then registered at the IMenuService and your contributions show up.
For creating an IContributionItem for a given command, you may use the CommandContributionItem class, which takes an CommandContributionItemParameter as constructor parameter. A CommandContributionItemParameter basicly contains all the required data for a command contribution known from the org.eclipse.ui.menus extension point.

private IContributionItem createContributionItem(IServiceLocator locator, Object contribSource) {
CommandContributionItemParameter contributionItemParameter = new CommandContributionItemParameter(locator, null, "", SWT.PUSH);
// pimp the item using the contribSource
return new CommandContributionItem(contributionItemParameter);

There you go.

One thought on “Programmatic command contributions”

Leave a Reply

Your email address will not be published. Required fields are marked *