一般来说,把 IContributionItem 或 IAction 加入 ToolBarManager中,只会显示相应的图标。
但如果想即显示 图标,又显示文字(就像 Perspective Shortcut)。怎么办?
看了源码,知道 Perspective Shortcut 的是处理 ToolItem, 调用 ToolItem.setText(...)。
所以,只要我能拿到 ToolBarManager 中的 ToolBar 中 ToolItem
但是: 在 ApplicationActionBarAdvisor 或者 ViewPart 中, 当你添加 action 时, 是得不到 ToolItem 的(还没初始化)
像这样:
于是,我写了以下帮助类,它是一个 ContributionItem
嘿,"这个时刻",总该让我得到 ToolItem 了吧! 见上面的 fill
然后, 我的 fillToolBar 大概像这样了:
...
但如果想即显示 图标,又显示文字(就像 Perspective Shortcut)。怎么办?
看了源码,知道 Perspective Shortcut 的是处理 ToolItem, 调用 ToolItem.setText(...)。
所以,只要我能拿到 ToolBarManager 中的 ToolBar 中 ToolItem
但是: 在 ApplicationActionBarAdvisor 或者 ViewPart 中, 当你添加 action 时, 是得不到 ToolItem 的(还没初始化)
像这样:
java 代码
- public class ApplicationActionBarAdvisor extends ActionBarAdvisor {
- ...
- protected void fillCoolBar(ICoolBarManager coolBar) {
- ToolBarManager menu = new ToolBarManager(SWT.FLAT | SWT.RIGHT);
- coolBar.add(menu);
- ... // 添加一些action
- ... // 但是如何让文字也显示在图标的右边呢?这里Toolbar 没有初始化,但我又不想让代码侵入其他部分.
- }
- ...
于是,我写了以下帮助类,它是一个 ContributionItem
java 代码
- public class ShowTextToolBarContributionItem extends ContributionItem {
- @Override
- public void fill(ToolBar parent, int index) {
- ToolItem[] toolItems = parent.getItems();
- for (ToolItem toolItem : toolItems) {
- ActionContributionItem contributionItem = (ActionContributionItem) toolItem.getData();
- IAction action = contributionItem.getAction();
- if (toolItem.getText() == null || toolItem.getText().length() == 0) {
- toolItem.setText(action.getText());
- }
- }
- }
- }
嘿,"这个时刻",总该让我得到 ToolItem 了吧! 见上面的 fill
然后, 我的 fillToolBar 大概像这样了:
java 代码
- protected void fillCoolBar(ICoolBarManager coolBar) {
- ToolBarManager menu = new ToolBarManager(SWT.FLAT | SWT.RIGHT);
- coolBar.add(menu);
- u.add(new ShowTextToolBarContributionItem()); // here
- }
...