CryptDemon CryptDemon - 6 months ago 94
Java Question

Programmatically add options to pulldown button in eclipse

In eclipse I have commands defined for buttons in the main button toolbar they have. I have one command/button in there that's set as a pulldown button and I'd like to programmatically add options to it. Kinda like how you can hit the little drop down button on the play button in eclipse and see different run scenarios. I want to be able to add options like that to my pulldown menu. I can't do it through the plugin editor because I need to generate the menu options dynamically.

So say I have the following pulldown button defined in my plugin.xml file. How do I add options to the pull down programmatically?

<menuContribution
allPopups="false"
locationURI="toolbar:org.eclipse.ui.main.toolbar">
<toolbar
id="com.company.gui.base.toolBarMain">
<command
commandId="com.company.gui.base.command1"
icon="icons/magnifier.png"
id="com.company.gui.base.toolBarMain.monitor"
label="Im a pulldown menu"
style="pulldown">
</command>
</toolbar>
</menuContribution>

Answer

Please find the below code.

private void addContextMenu(SampleContributionFactory fac) {
     final IMenuService menuService = (IMenuService) PlatformUI.getWorkbench().getService (IMenuService.class);
     menuService.addContributionFactory(fac);
}

class SampleContributionFactory extends AbstractContributionFactory{

    SampleContributionFactory(final String menuID) {
        super("menu:" + menuID, null);
    }

    @Override
    public void createContributionItems(IServiceLocator serviceLocator,
            IContributionRoot additions) {      
        // add Command Contribution item
        additions.addContributionItem(<YOUR CONTRIBUTION ITEM>, null);
    // add one more Command Contribution item
    ....
    } 
}

Now create an object of SampleContributionFactory as below.

  SampleContributionFactory fac = new SampleContributionFactory ("com.company.gui.base.toolBarMain.monitor");

and call the method

addContextMenu(fac);

TODO : add command contribution items in the SampleContributionFactory as required by you.

Comments