Creating an OPM GEF Editor – Part 21: Adding Keyboard Shortcuts

Previous Tutorial: Creating an OPM GEF Editor – Part  20: Creating a Context Menu and Adding Custom Actions

Keyboard shortcuts are very useful for activating actions. There are many shortcuts that are common in all environments – and for better usability, enabling this shortcuts give the user a better user experience. In my case, I wanted to let the user edit the name of a thing (or state) using the F2 key, which is commonly used for this purpose.

Adding keyboard shortcuts to GEF is fairly easy. You only need to define a <code>KeyHandler</code> and attach it to the graphical viewer. I defined two key shortcuts: F2 for direct editing, and F3 for my own ResizeToContentsAction action.

	private void configureKeyboardShortcuts() {
		getGraphicalViewer().getKeyHandler();<br> GraphicalViewerKeyHandler keyHandler = new GraphicalViewerKeyHandler(getGraphicalViewer())
		keyHandler.put(KeyStroke.getPressed(SWT.F2, 0), getActionRegistry().getAction(GEFActionConstants.DIRECT_EDIT));
		keyHandler.put(KeyStroke.getPressed(SWT.F3, 0),
				getActionRegistry().getAction(ResizeToContentsAction.RESIZE_TO_CONTENTS_ID));
		getGraphicalViewer().setKeyHandler(keyHandler);
	}

This function is called from the configureGraphicalViewer. And that is all! You can find the source for this change in my github repository: https://github.com/vainolo/Object-Process-Programming.

Next tutorial: Creating an OPM GEF Editor – Part 22: Enabling Select-All Action in a GEF Editor

Enhanced by Zemanta

4 thoughts on “Creating an OPM GEF Editor – Part 21: Adding Keyboard Shortcuts

  1. Keyboard Shortcuts doesnot seems to work. When I pressed F2, basically there is no effect. Any clues??

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.