JFace/SWT:将带有命令的工具栏添加到分区的最佳方法是什么?



我有一个部分,想给它添加一个工具栏。我能够使用操作以编程方式做到这一点,但要求是尽可能多地以声明方式(在插件.xml中)做到这一点。所以我想为每个工具栏按钮定义一个命令和一个处理程序,但我不知道如何将它们添加到该部分的工具栏中。有什么方法可以在插件.xml中以声明方式做到这一点吗?如果没有,我该如何以编程方式执行此操作?

谢谢!

我认为您必须编写自己的扩展点来定义plugin.xml中的内容,然后编写代码以访问扩展点注册表以获取声明的扩展并从信息中创建工具栏。

有关更多详细信息,请参阅 Eclipse 扩展点和扩展。

你需要看看如何使用org.eclipse.ui.menus extension点。它支持将命令/小部件添加到菜单/弹出窗口/工具栏/修剪。

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

下面是如何为分区创建工具栏的示例,请确保在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);
}

如果要将声明的命令从plugin.xml添加到工具栏,请查看CommandContributionItem

toolBarManager.add(new CommandContributionItem(new CommandContributionItemParameter(getSite(), "id", "commandId", SWT.NONE)));

最新更新