我正在开发一组 Eclipse 插件,其中一个插件负责向 Eclipse 工作区添加工具栏。
虽然可以在 plugin.xml
中添加新命令(和相应的按钮),但我还需要一个文本框和一个标签,这需要添加一个 Control
到 plugin.xml
,加上一个扩展 org.eclipse.ui.menus.WorkbenchWindowControlContribution
的 Java 实现。实际上,这归结为重写子类中的 createControl(Composite parent)
。
这部分我很清楚。问题是我不确定应该返回哪种类型的 Control 对象。
我尝试了以下方法:
创建一个
ToolBarManager
,向其添加一个 SWTLabel
和一个 STWText
(均包装在单独的ControlContribution 中
对象),返回ToolBarManager.createControl(parent)
获取的工具栏:@Override protected Control createControl(Composite parent) { ToolBarManager manager = new ToolBarManager(SWT.FLAT | SWT.HORIZONTAL); LabelContributionItem labelItem = new LabelContributionItem("myLabelId"); manager.add(labelItem); TextContributionItem textItem = new TextContributionItem("myTextId"); manager.add(textItem); ToolBar toolbar = manager.createControl(parent); return toolbar; }
但是,标签没有正确定位:
使用
GridLayout
作为控件返回(代码改编自 this answer ):@Override protected Control createControl(Composite parent) { Composite composite = new Composite(parent, SWT.SINGLE); GridLayout compositeLayout = new GridLayout(2, false); compositeLayout.marginTop = -1; compositeLayout.marginBottom = 0; compositeLayout.marginLeft = 5; compositeLayout.marginWidth = 0; composite.setLayout(compositeLayout); Label myLabel = new Label(composite, SWT.BORDER | SWT.SINGLE); myLabel.setText("myLabel"); Text myText = new Text(composite, SWT.BORDER | SWT.SINGLE); myText.setText("myText"); return composite; }
结果是一个大小和对齐不正确的文本框,加上标签周围的边框(添加最右边的文本框用于比较):
我还尝试了其他一些组合和布局,但无法使其正常工作。此外,我想添加一个 ControlDecoration到文本框,像这样:
要使 ControlDecoration 的鼠标悬停文本正常工作,文本框左侧需要有边距空间 ( source ):
Clients using ControlDecoration should typically ensure that enough margin space is reserved for a decoration
添加这个空间也被证明很麻烦,除非使用 GridLayout 的 marginLeft
参数(但 GridLayout 给出了上述对齐问题)。
最佳答案
我在标签方面遇到了同样的问题。如果要向工具栏添加文本,请使用 CLabel
。
关于java - 将自定义控件添加到 Eclipse 工具栏的正确方法是什么(使用 WorkbenchWindowControlContribution)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28900682/