最近在学习GEF-whole-upload那本书,在模仿书上例子的过程中,想给里面的图形编辑器增加一些快捷键,比如Ctrl+A(全选图
形),Ctrl+S(保存)等等。
最初的想法是再Editor的setKeyHandler方法里面,使用KeyStroke类,注册Ctrl+A,Ctrl+S等键盘事件:
private void setKeyHandler() {
KeyHandler keyHandler = new KeyHandler();
...
keyHandler.put(KeyStroke.getPressed('a', 0x1, SWT.CTRL),
getActionRegistry().getAction(ActionFactory.SELECT_ALL.getId()));
getGraphicalViewer().setKeyHandler(
new GraphicalViewerKeyHandler(getGraphicalViewer())
.setParent(keyHandler));
但是经过试验,这种方法无法响应Ctrl+A事件。具体原因不清楚,上网查了很多资料得不到解答。后来和傻鸟大哥讨论了一下这个问题,他认为是有更高级
的注册机制存在,屏蔽了以这种形式注册的Ctrl+A事件的响应。
今天咖啡老大刚好有空,向他请教了这个问题,终于得到解决的方法。(老大果然厉害!万分感谢!)
具体的解决方法如下:
1. 修改ApplicationActionBarAdvisor.java:在makeActions方法里面添加:
selectAll = ActionFactory.SELECT_ALL.create(window);
register(selectAll);
2. 给Editor增加一个getAction的方法:
public IAction getAction(String key) {
return getActionRegistry().getAction(key);
3. 再在DiagramActionBarContributor.java里面的setActiveEditor方法中添加:
actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(),
action);
actionBars.updateActionBars();
注意:actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(),
action) 的第二个参数action是需要通过Editor来获取的。因此,最后
DiagramActionBarContributor.java文件的修改为:
protected IAction getAction(IEditorPart editor, String actionID) {
if (editor instanceof DiagramEditor) {
return ((DiagramEditor) editor).getAction(actionID);
}
return null;
public void setActiveEditor(IEditorPart activeEditor) {
IActionBars actionBars = this.getActionBars();
actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(),
getAction(activeEditor, ActionFactory.SELECT_ALL.getId()));
actionBars.updateActionBars();
到此为止,图形编辑器可以响应Ctrl+A实现全选。