GEF-通过绑定键盘事件实现快捷键功能

来源:互联网 发布:单片机的用途 编辑:程序博客网 时间:2024/09/21 09:26

本文中涉及到的例子可以在以下URL下载。导入eclipse项目即可,我的环境的Eclipse4.3.1

http://download.csdn.net/detail/hoslay1/6925761

如果有问题请联系我QQ:195307039说明来意即可。

以下Editor代表外部的编辑器,EditPart代表GEF的EditPart



GEF中如果希望在画板上通过快捷键来操作EditPart如:delete或者Ctrl+Z等等

可以通过KeyHandler来实现,以下是实现方式:

在Editor的configureGraphicalViewer方法中,创建一个KeyHandler对象,并设置其与Action的绑定,最后将KeyHandler对象设置到viewer上。

@Overrideprotected void configureGraphicalViewer() {super.configureGraphicalViewer();viewer = getGraphicalViewer();//设置partFactoryviewer.setEditPartFactory(new PartFactory());//创建键盘处理的句柄KeyHandler keyHandler = new KeyHandler();//按delete时删除action,发起DELETE类型的事件,然后捕获keyHandler.put(KeyStroke.getPressed(SWT.DEL, 127, 0), getActionRegistry().getAction(GEFActionConstants.DELETE));//按F2时编辑keyHandler.put(KeyStroke.getPressed(SWT.F2, 0), getActionRegistry().getAction(GEFActionConstants.DIRECT_EDIT));//按Ctrl+Z撤销keyHandler.put(KeyStroke.getReleased('',122,SWT.CTRL), getActionRegistry().getAction(GEFActionConstants.UNDO));//按Ctrl+Y反撤销keyHandler.put(KeyStroke.getReleased('',121,SWT.CTRL), getActionRegistry().getAction(GEFActionConstants.REDO));//按Ctrl+A全选keyHandler.put(KeyStroke.getReleased('',97,SWT.CTRL), getActionRegistry().getAction(GEFActionConstants.SELECT_ALL));//按F3弹出一个dialog,快捷键也可以基于此类的实现或者是GraphicalViewerHandler//keyHandler.put(KeyStroke.getPressed(SWT.F3, 0), getActionRegistry().getAction("TestDialog"));//GraphicalViewerKeyHandler可实现自定义快捷键以及键盘移动等功能viewer.setKeyHandler(keyHandler);}

keyHandler的put方法就是将键盘行为与action进行绑定
KeyStroke.getPressed取得的是某个单键按下的行为
KeyStroke.getReleased取得的是组合按键按下的行为
getActionRegistry().getAction可以取得在这个Editor上生效的Action
最后viewer.setKeyHandler(keyHandler);将这组绑定设置到viewer上

DIRECT_EDITAction定义在当前Editor中,而其它的Action定义在父类GraphicalEditor中

Action必须要先创建并且注册才能在这里被取出来

这里贴上父类的代码:

protected void createActions() {ActionRegistry registry = getActionRegistry();IAction action;action = new UndoAction(this);registry.registerAction(action);getStackActions().add(action.getId());action = new RedoAction(this);registry.registerAction(action);getStackActions().add(action.getId());action = new SelectAllAction(this);registry.registerAction(action);action = new DeleteAction((IWorkbenchPart) this);registry.registerAction(action);getSelectionActions().add(action.getId());action = new SaveAction(this);registry.registerAction(action);getPropertyActions().add(action.getId());registry.registerAction(new PrintAction(this));}

GEFActionConstants.DELETE等就是这些Action的ID属性,通过这个ID属性就能找到这个Action,自定义的Action的获取就能通过那个ID。

0 0
原创粉丝点击