JFace/SWT: What is the best way to add a toolbar with Commands to a Section?

我的未来我决定 提交于 2019-12-11 13:39:39

问题


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!


回答1:


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.




回答2:


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);



回答3:


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)));


来源:https://stackoverflow.com/questions/21851929/jface-swt-what-is-the-best-way-to-add-a-toolbar-with-commands-to-a-section

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!