Editor与视图的区别不仅在于那个经典的打开-->修改-->保存。
它还体现在,视图有自己的独有的工具栏,下拉菜单,而编辑器是共享通用的菜单栏和工具栏。
IEditorActionBarContributor类负责为一个或多个编辑器向主菜单栏和工具栏添加操作。
通常是编辑器打开时添加共享菜单栏和工具栏,编辑器关闭时(同一类型的全部关闭),dispose共享的菜单栏和工具栏。
EditorActionBarContributor是IEditorActionBarContributor接口的标准实现,如果我们需要为编辑器
添加共享的操作,可以实现如下方法:
/**
* Contributes to the given menu.
假如你需要为打开的EditorPart添加菜单,实现此方法
*/
public void contributeToMenu(IMenuManager menuManager) {
}
/**
* Contributes to the given status line.
*/
public void contributeToStatusLine(IStatusLineManager statusLineManager) {
}
/**
* Contributes to the given tool bar.
*/
public void contributeToToolBar(IToolBarManager toolBarManager) {
}
/**
* Contributes to the given cool bar.
*/
public void contributeToCoolBar(ICoolBarManager coolBarManager) {
}
另外,重点说一下setActiveEditor方法。此方法在打开编辑器时调用。
一般,我们会在此方法中引用全局的activeEditor,也可能会关联RetargetAction。
按照有样学样法则,我们先看一下eclipse中的基本实现:
好的。我们看看gef中的ActionBarContributor是如何实现的吧。
先看看setActiveEditor的实现:
public void setActiveEditor(IEditorPart editor) {
ActionRegistry registry = (ActionRegistry)editor.getAdapter(ActionRegistry.class);
IActionBars bars = getActionBars();
for (int i = 0; i < globalActionKeys.size(); i++) {
String id = (String)globalActionKeys.get(i);
bars.setGlobalActionHandler(id, registry.getAction(id));//关联Retarget Action(hook)
}
}
再看看开源RCP应用ZDT的一个基本实现:
public class CategoryEditorActionBarContributor extends
EditorActionBarContributor {
private AddEntryAction addEntryAction;
private EditEntryAction editEntryAction;
//创建Action,并添加至至Edit菜单下
public void contributeToMenu(IMenuManager menuManager) {
addEntryAction = new AddEntryAction();
addEntryAction.setToolTipText("Add an entry");
editEntryAction = new EditEntryAction();
addEntryAction.setToolTipText("Edit an entry");
IMenuManager editMenu = menuManager.findMenuUsingPath("edit");
editMenu.add(new Separator());
editMenu.add(addEntryAction);
editMenu.add(editEntryAction);
}
//
public void setActiveEditor(IEditorPart targetEditor) {
addEntryAction.setActiveEditor(targetEditor);
editEntryAction.setActiveEditor(targetEditor);//将打开的Editor传递给Action
targetEditor.getSite().getPage().addSelectionListener(editEntryAction);
}
}
public class AddEntryAction extends Action
{
private IEditorPart editor;
private final static String ID = "net.sourceforge.zdt.flashcard.commands.addEntry";
public AddEntryAction()
{
this.setText("&Add Entry");
this.setId("#Add Entry");
this.setActionDefinitionId(ID);
}
public void run()
{
CategoryEditor charEditor = (CategoryEditor)editor;//取得激活的EditorPart
AddEntryWizard wizard = new AddEntryWizard();
// Instantiates the wizard container with the wizard and opens
// it
WizardDialog dialog = new WizardDialog(Display.getDefault()
.getActiveShell(), wizard);
dialog.create();
if (dialog.open() == Window.OK) {
EntryValue ev = wizard.getEntryValue();
charEditor.addEntryToUI(ev, true);
}
}
public void setActiveEditor(IEditorPart targetEditor)
{
editor = targetEditor;
}
}
总的来说,EditorActionBarContributor还是很简单的。