Shortcut Keys

Vaadin provides simple ways to define shortcut keys for field components, as well as to a default button, and a lower-level generic shortcut API based on actions.

A shortcut is an action that is executed when a key or key combination is pressed within a specific scope in the UI. The scope can be the entire UI or a Window inside it.

Shortcut Keys for Default Buttons

You can add a click shortcut to a button to set it as “default” button; pressing the defined key, typically Enter, in any component in the scope (sub-window or UI) causes a click event for the button to be fired.

You can define a click shortcut with the setClickShortcut() shorthand method:

Java

  1. // Have an OK button and set it as the default button
  2. Button ok = new Button("OK");
  3. ok.setClickShortcut(KeyCode.ENTER);
  4. ok.addStyleName(ValoTheme.BUTTON_PRIMARY);

The setClickShortcut() is a shorthand method to create, add, and manage a ClickShortcut, rather than to add it with addShortcutListener().

Themes offer special button styles to show that a button is special. In the Valo theme, you can use the BUTTON_PRIMARY style name. The result can be seen in Default Button with Click Shortcut.

shortcut defaultbutton

Default Button with Click Shortcut

Field Focus Shortcuts

You can define a shortcut key that sets the focus to any focusable component (implements Focusable), usually field components, by adding a FocusShortcut as a shortcut listener to the component.

The constructor of the FocusShortcut takes the focusable component as its first parameter, followed by the key code, and an optional list of modifier keys, as listed in Supported Key Codes and Modifier Keys.

Java

  1. // A field with Alt+N bound to it
  2. TextField name = new TextField("Name (Alt+N)");
  3. name.addShortcutListener(
  4. new FocusShortcut(name, KeyCode.N,
  5. ModifierKey.ALT));
  6. layout.addComponent(name);

You can also specify the shortcut by a shorthand notation, where the shortcut key is indicated with an ampersand ( &).

Java

  1. // A field with Alt+A bound to it, using shorthand notation
  2. TextField address = new TextField("Address (Alt+A)");
  3. address.addShortcutListener(
  4. new FocusShortcut(address, "&Address"));

This is especially useful for internationalization, so that you can determine the shortcut key from the localized string.

Generic Shortcut Actions

Shortcut keys can be defined as actions using the ShortcutAction class. It extends the generic Action class that is used for example in Tree and Table for context menus. Currently, the only classes that accept ShortcutActions are Window and Panel.

To handle key presses, you need to define an action handler by implementing the Handler interface. The interface has two methods that you need to implement: getActions() and handleAction().

The getActions() method must return an array of Action objects for the component, specified with the second parameter for the method, the sender of an action. For a keyboard shortcut, you use a ShortcutAction. The implementation of the method could be following:

Java

  1. // Have the unmodified Enter key cause an event
  2. Action action_ok = new ShortcutAction("Default key",
  3. ShortcutAction.KeyCode.ENTER, null);
  4. // Have the C key modified with Alt cause an event
  5. Action action_cancel = new ShortcutAction("Alt+C",
  6. ShortcutAction.KeyCode.C,
  7. new int[] { ShortcutAction.ModifierKey.ALT });
  8. Action[] actions = new Action[] {action_cancel, action_ok};
  9. public Action[] getActions(Object target, Object sender) {
  10. if (sender == myPanel)
  11. return actions;
  12. return null;
  13. }

The returned Action array may be static or you can create it dynamically for different senders according to your needs.

The constructor of ShortcutAction takes a symbolic caption for the action; this is largely irrelevant for shortcut actions in their current implementation, but might be used later if implementors use them both in menus and as shortcut actions. The second parameter is the key code and the third a list of modifier keys, which are listed in Supported Key Codes and Modifier Keys.

The following example demonstrates the definition of a default button for a user interface, as well as a normal shortcut key, Alt+C for clicking the Cancel button.

Java

  1. public class DefaultButtonExample extends CustomComponent
  2. implements Handler {
  3. // Define and create user interface components
  4. Panel panel = new Panel("Login");
  5. FormLayout formlayout = new FormLayout();
  6. TextField username = new TextField("Username");
  7. TextField password = new TextField("Password");
  8. HorizontalLayout buttons = new HorizontalLayout();
  9. // Create buttons and define their listener methods.
  10. Button ok = new Button("OK", event -> okHandler());
  11. Button cancel = new Button("Cancel", event -> cancelHandler());
  12. // Have the unmodified Enter key cause an event
  13. Action action_ok = new ShortcutAction("Default key",
  14. ShortcutAction.KeyCode.ENTER, null);
  15. // Have the C key modified with Alt cause an event
  16. Action action_cancel = new ShortcutAction("Alt+C",
  17. ShortcutAction.KeyCode.C,
  18. new int[] { ShortcutAction.ModifierKey.ALT });
  19. public DefaultButtonExample() {
  20. // Set up the user interface
  21. setCompositionRoot(panel);
  22. panel.addComponent(formlayout);
  23. formlayout.addComponent(username);
  24. formlayout.addComponent(password);
  25. formlayout.addComponent(buttons);
  26. buttons.addComponent(ok);
  27. buttons.addComponent(cancel);
  28. // Set focus to username
  29. username.focus();
  30. // Set this object as the action handler
  31. panel.addActionHandler(this);
  32. }
  33. /**
  34. * Retrieve actions for a specific component. This method
  35. * will be called for each object that has a handler; in
  36. * this example just for login panel. The returned action
  37. * list might as well be static list.
  38. */
  39. public Action[] getActions(Object target, Object sender) {
  40. System.out.println("getActions()");
  41. return new Action[] { action_ok, action_cancel };
  42. }
  43. /**
  44. * Handle actions received from keyboard. This simply directs
  45. * the actions to the same listener methods that are called
  46. * with ButtonClick events.
  47. */
  48. public void handleAction(Action action, Object sender,
  49. Object target) {
  50. if (action == action_ok) {
  51. okHandler();
  52. }
  53. if (action == action_cancel) {
  54. cancelHandler();
  55. }
  56. }
  57. public void okHandler() {
  58. // Do something: report the click
  59. formlayout.addComponent(new Label("OK clicked. "
  60. + "User=" + username.getValue() + ", password="
  61. + password.getValue()));
  62. }
  63. public void cancelHandler() {
  64. // Do something: report the click
  65. formlayout.addComponent(new Label("Cancel clicked. User="
  66. + username.getValue() + ", password="
  67. + password.getValue()));
  68. }
  69. }

Notice that the keyboard actions can currently be attached only to Panels and Windows. This can cause problems if you have components that require a certain key. For example, multi-line TextField requires the Enter key. There is currently no way to filter the shortcut actions out while the focus is inside some specific component, so you need to avoid such conflicts.

Supported Key Codes and Modifier Keys

The shortcut key definitions require a key code to identify the pressed key and modifier keys, such as Shift, Alt, or Ctrl, to specify a key combination.

The key codes are defined in the ShortcutAction.KeyCode interface and are:

Keys A to Z

Normal letter keys

F1 to F12

Function keys

BACKSPACE, DELETE, ENTER, ESCAPE, INSERT, TAB

Control keys

NUM0 to NUM9

Number pad keys

ARROW_DOWN, ARROW_UP, ARROW_LEFT, ARROW_RIGHT

Arrow keys

HOME, END, PAGE_UP, PAGE_DOWN

Other movement keys

Modifier keys are defined in ShortcutAction.ModifierKey and are:

ModifierKey.ALT

Alt key

ModifierKey.CTRL

Ctrl key

ModifierKey.SHIFT

Shift key

All constructors and methods accepting modifier keys take them as a variable argument list following the key code, separated with commas. For example, the following defines a Ctrl+Shift+N key combination for a shortcut.

Java

  1. TextField name = new TextField("Name (Ctrl+Shift+N)");
  2. name.addShortcutListener(
  3. new FocusShortcut(name, KeyCode.N,
  4. ModifierKey.CTRL,
  5. ModifierKey.SHIFT));

Supported Key Combinations

The actual possible key combinations vary greatly between browsers, as most browsers have a number of built-in shortcut keys, which can not be used in web applications. For example, Mozilla Firefox allows binding almost any key combination, while Opera does not even allow binding Alt shortcuts. Other browsers are generally in between these two. Also, the operating system can reserve some key combinations and some computer manufacturers define their own system key combinations.