Enter-key shortcut handler while still allowing Enter in TextArea?

At the top of my View I have a set of Search fields, with a Search Button.
The Search button has addClickShortcut(Key.ENTER)

Further down I have a TextArea where I’d like the user to also be able to use the Enter key. How can I achieve that?

Ideally, I think I’d prefer the addClickShortcut(Key.ENTER) to only apply when the focus is somewhere in the search layout. That way it would work in the TextArea, and I could have local Enter-shortcuts multiple places in the same view

You can add a shortcut listener limited to a specific component if you use the custom shortcut API. The scoping is done with the .listenOn call on the shortcut registration, which is returned by the addShortcutListener method. See the docs here: Keyboard Shortcuts | Creating UI | Vaadin Docs

1 Like

Thanks Olli :smiley:,

That did exactly what I wanted:

// button.addClickShortcut(Key.ENTER);

Command command = () -> {
    button.click();
};

Shortcuts.addShortcutListener(layout, command, Key.ENTER)
    .listenOn(layout)
    .resetFocusOnActiveElement();

The “resetFocusOnActiveElement” is needed so that the text in the current field is flushed before the button is “clicked”. As a side-effect, since all our fields have setAutoselect(true), that also selects the text. Don’t think that is a problem.