Docs

Documentation versions (currently viewingVaadin 25 (prerelease))

Keyboard Shortcuts

Adding keyboard shortcuts to components for a better user experience.

Shortcuts allow you to assign keyboard shortcuts to your components to improve end-user experience. You can add predefined shortcuts, create your own custom shortcuts, and configure the reaction when a shortcut is triggered.

A shortcut key combination consists of one primary key, and zero to four key modifiers (i.e., Alt, Ctrl, Meta, Shift).

Adding Click Shortcuts

Click shortcuts define alternatives to the click action in components that implement the ClickNotifier interface. Add a click shortcut using the ClientNotifier.addClickShortcut(…​) method.

Example 1. Triggering a button click with the Enter key
Source code
Java
TextField userName = new TextField("User name");
PasswordField password = new PasswordField("Password");

Button login = new Button("Login");
login.addClickListener(event -> this.login());
login.addClickShortcut(Key.ENTER);

Adding Focus Shortcuts

Focus shortcuts place the focus on a Focusable component, like an input field. Add a focus shortcut using the Focusable.addFocusShortcut(…​) method.

Example 2. Focusing a text field with the Alt+F key combination
Source code
Java
TextField textField = new TextField("Label");
textField.addFocusShortcut(Key.KEY_F, KeyModifier.ALT);

Adding Custom Shortcuts

Use the UI.addShortcutListener(…​) method to add a shortcut that executes a Command when triggered. The Command can be a lambda, or a reference to a void method that accepts no arguments.

Example 3. Calling the openCustomerCreation() method with the Ctrl+Alt+N key combination
Source code
Java
UI.getCurrent().addShortcutListener(
        this::openCustomerCreation, Key.KEY_N,
        KeyModifier.CONTROL, KeyModifier.ALT);

// Elsewhere in the class:
private void openCustomerCreation() {
    // Open the new customer form
}

Customizing Shortcuts

Every add…​Shortcut(…​) method returns a ShortcutRegistration object that can be used to further configure the shortcut.

Configuring Active Scope

By default, shortcuts are registered to the global scope. This means that the shortcut is triggered when the user presses the correct keys, regardless of the location of their cursor, or which element is in focus on the screen.

Use the ShortcutRegistration.listenOn(…​) method to define a specific component as the scope where the shortcut is active.

Example 4. Clearing the input fields when Esc is pressed, but only when the focus is inside the Scope component
Source code
Java
public class Scope extends Div {
    public Scope() {
        TextField firstName = new TextField();
        TextField lastName = new TextField();

        add(firstName, lastName);

        Command command = () -> {
            firstName.setValue("");
            lastName.setValue("");
            firstName.focus();
        };
        // first parameter is the lifecycle owner
        // of the shortcut and it is discussed later.
        Shortcuts.addShortcutListener(this, 1
                    command, Key.ESCAPE)
                // defines the component onto which
                // the shortcuts listener is attached:
                .listenOn(this); 2
    }
}
  1. The shortcut is created using the factory class Shortcuts, which offers the most generic method for creating shortcuts. See Shortcut Lifecycle Owners below for more.

  2. The shortcut is tied to the parent component (Scope) of the input components. If the user types into either TextField and then presses Esc, both input fields are cleared and focus is returned to the first field.

Removing Shortcuts

Remove a registered shortcut using the ShortcutRegistration.remove() method.

Example 5. Removing a focus shortcut
Source code
Java
TextField textField = new TextField("Label");
ShortcutRegistration registration =
        textField.addFocusShortcut(Key.KEY_F,
            KeyModifier.ALT);

// something happens here

registration.remove(); // shortcut removed!
Note
Some shortcut registration methods return a Registration object instead of a ShortcutRegistration object. In these cases, use the Registration.remove() method to remove the shortcut.

Shorthands for Shortcut Modifiers

ShortcutRegistration provides shorthand methods for assigning key modifiers to a shortcut.

Example 6. Using the shorthand methods to assign key modifiers
Source code
Java
Input input = new Input();
// The focus shortcut is triggered with Alt+Shift+F
input.addFocusShortcut(Key.KEY_F).withAlt().withShift();

// You can also use withModifiers() to set both modifiers at once:
input.addFocusShortcut(Key.KEY_F)
        .withModifiers(KeyModifier.ALT, KeyModifier.SHIFT);

// To remove the modifiers, call withModifiers() without parameters:
input.addFocusShortcut(Key.KEY_F)
        .withModifiers(); // no modifiers

Shortcut Event Behavior on Client Side

ShortcutRegistration provides methods to define the behavior of events on the client side. With browser DOM events, you can control whether an event should propagate upwards in the DOM tree (i.e., component hierarchy), and whether it should allow default browser behavior.

By default, shortcuts consume the event. This means that events don’t propagate upwards in the DOM tree (component hierarchy). Also, the default browser behavior is prevented. For example, the characters used in the shortcut aren’t inserted into the input field, or clicking on a link prevents the browser from following the URL. See Event.preventDefault() for more information.

As an exception, click shortcuts created with the ClickNotifier::addClickShortcut(…​) method allows default browser behavior.

You can change the default behavior using the following methods:

  • allowEventPropagation() (fluent)

  • allowBrowserDefault() (fluent)

  • setEventPropagationAllowed(boolean)

  • setBrowserDefaultAllowed(boolean)

Example 7. Allowing default browser behavior for a focus shortcut
Source code
Java
Input input = new Input();
input.addFocusShortcut(Key.KEY_F)
        // the character 'f' is entered into the input, if it's focused
        .allowBrowserDefault();
Example 8. Allowing event propagation for a focus shortcut
Source code
Java
TextField name = new TextField("Name");
TextField address = new TextField("Address");
VerticalLayout form = new VerticalLayout(name, address);
add(form);

name.addFocusShortcut(Key.KEY_N, KeyModifier.CONTROL)
        .listenOn(form)
        // the shortcut event is propagated from the text field to the
        // form and higher in the hierarchy
        .allowEventPropagation(); 1

// the listener attached to the view (this) can now catch the
// shortcut event and change the form styles
Shortcuts.addShortcutListener(this,
        () -> form.setClassName("red-border"),
        Key.KEY_N, KeyModifier.CONTROL)
        .listenOn(this); 2
  1. Once the name field has focus and the shortcut is activated, the event is propagated higher in the component hierarchy.

  2. The view also catches the same shortcut event and applies a CSS class to the form.

Resetting Focus Before Shortcut Activation

Sometimes it’s necessary to ensure that the currently focused element loses and regains focus before a shortcut is activated. This is useful when the focused element has pending value changes that need to be sent to the server before the shortcut is triggered. ShortcutRegistration provides two methods for this:

  • resetFocusOnActiveElement() (fluent)

  • setResetFocusOnActiveElement(boolean)

Example 9. Ensuring that any changes to the description field are submitted to the server before saving if Ctrl+Enter is pressed while the field is focused
Source code
Java
TextField description = new TextField("Description");
// ON_CHANGE is the default mode, but we explicitly set it here for clarity
description.setValueChangeMode(ValueChangeMode.ON_CHANGE);

Button save = new Button("Save");
save.addClickListener(event -> this.save());
save.addClickShortcut(Key.ENTER, KeyModifier.CONTROL).resetFocusOnActiveElement();

Checking Shortcut States

ShortcutRegistration offers a variety of methods to check the internal state of a shortcut. Additionally, you can use the boolean isShortcutActive() method to check whether the shortcut is enabled on the client side.

See the JavaDoc API documentation for details.

Shortcut Lifecycle Owners

Shortcuts have a lifecycle that’s controlled by an associated Component, called the lifecycle owner component. When the component acting as a lifecycle owner is both attached, enabled, and visible, the shortcut is active. If these conditions aren’t met, the shortcut can’t be triggered.

For focus and click shortcuts, the lifecycle owner is the component itself.

For shortcuts registered through UI, the lifecycle owner is the UI. This means that the shortcut remains active until you remove it.

Use the Shortcuts.addShortcutListener(…​) method to create a shortcut with a lifecycle bound to a specific component.

Example 10. Binding a shortcut to the lifecycle of a Paragraph component
Source code
Java
Paragraph paragraph =
        new Paragraph("When you see me, try Alt+G!");

Shortcuts.addShortcutListener(paragraph,
        () -> Notification.show("Well done!"),
        Key.KEY_G, KeyModifier.ALT);

add(paragraph);

You can change the lifecycle owner of a shortcut after its creation using the ShortcutRegistration.bindLifecycleTo(…​) method.

Example 11. Binding the lifecycle of a button click shortcut to a Grid component
Source code
Java
Grid<User> usersList = new Grid<>();
Button newUserButton = new Button("Add user", event -> {
        // show new user form
});
newUserButton.addClickShortcut(Key.KEY_N, KeyModifier.CONTROL)
        .bindLifecycleTo(usersList); 1
  1. The shortcut is active while the usersList component is visible on the page. Once the usersList component is detached or it becomes invisible, the shortcut is no longer active.

Listening for Shortcut Events

The UI.addShortcutListener(…​) method has an overload method that accepts a ShortcutEventListener instead of a Command. When the shortcut is detected, the event listener receives a ShortcutEvent that contains the following information:

  • the Key,

  • KeyModifiers,

  • the listenOn component (accessible via the ShortcutEvent.getSource() method), and

  • the lifecycle owner component (accessible via the ShortcutEvent.getLifecycleOwner() method).

Example 12. Using a single listener for multiple shortcuts
Source code
Java
// handles multiple shortcuts
ShortcutEventListener listener = event -> {
   if (event.matches(Key.KEY_G, KeyModifier.ALT)) {
       // do something G-related
   }
   else if (event.matches(Key.KEY_J, KeyModifier.ALT)) {
       // do something J-related
   }
};

UI.getCurrent().addShortcutListener(listener,
        Key.KEY_G, KeyModifier.ALT);
UI.getCurrent().addShortcutListener(listener,
        Key.KEY_J, KeyModifier.ALT);

C949BD20-2809-4BD0-81FF-9A9A4E6F96E5