Wednesday, March 14, 2012

Eclipse RCP - How to create toolbar dynamically

Eclipse supports the dynamic creation of menus and toolbars using the menuContribution extension point. The class attribute of menuContribution specifies the Java Class to be used for dynamic creation. The custom java class must extend ExtensionContributionFactory

image

Following example adds Exit toolbar button

public class ToolbarProvider extends ExtensionContributionFactory
{

    public ToolbarProvider()
    {
    }

    @Override
    public void createContributionItems( IServiceLocator serviceLocator, IContributionRoot additions )
    {
        ToolBarContributionItem toolbar = new ToolBarContributionItem( );
        additions.addContributionItem( toolbar, null );
        CommandContributionItemParameter p = new CommandContributionItemParameter( serviceLocator, "", "org.eclipse.ui.file.exit",
                SWT.PUSH );
        p.label = "Exit";
        p.icon = Activator.getImageDescriptor( "icons/alt_window_16.gif" );
        CommandContributionItem item = new CommandContributionItem( p );
        item.setVisible( true );
       
        toolbar.getToolBarManager().add( item );
    }

}

Similarly to add a menu the object of CommandContributionItem can be used if locationURI points to a menu.

3 comments:

  1. Very nice, and it is exactly what I need. I have tryied your code, but I cannot display the dynamic toolbar, I have created a dynamic item in my plugin pointing to this class without succed.

    So, would you guide me about how to show the dynamic toolbar in the toolbar:org.eclipse.ui.main.toolbar URI?

    Thanks

    ReplyDelete
    Replies
    1. Hi Mar,

      Can you share the sample project you have created. I can look at the code and will try to figure out the exact issue. You can email me the sample code at asheesh.arora@gmail.com

      Regards
      Asheesh

      Delete
  2. This blog is really good..
    Exactly the same way we can create menus dynamically. For that we need to use MenuManager in place of ToolBarContributionItem and in place of
    getToolBarManager() we have to use simply add() with the MenuManager object.

    ReplyDelete