Search code examples
javatextareavaadinkeypress

How to detect enter key press in vaadin TextArea


I am using a vaadin TextArea as a rough console. The user can enter commands which should be executed when he presses the enter key. Is there a way to specify this with a listener on the TextArea?

The closest thing I found is to use:

TextArea textArea = new TextArea();
textArea.addTextChangeListener(this);
textArea.setTextChangeEventMode(TextChangeEventMode.EAGER);

And handle the text change event:

@Override
public void textChange(TextChangeEvent event) {
   System.out.println(event.getText());
}

This is however triggered as soon as text has been entered in the TextArea. I would like to be notified only when the enter key has been pressed.


Solution

  • You cannot listen to shortcut keys on the textarea itself, but a simple solution would be to add a submit button and use enter as it's shortcut:

    Button b = new Button("submit", new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {
            // handle your event
        }
    });
    layout.addComponent(b);
    b.setClickShortcut(KeyCode.ENTER);
    

    You can hide the button itself if you don't wish it:

    b.setVisible(false);
    

    Another solution would be to use ShortcutActions and Handlers as described in here: https://vaadin.com/book/-/page/advanced.shortcuts.html

    But in either case you have to take into account that listening to enter key will cause a conflict when using a TextArea component because you also need to use the same key to get to the next line in the TextArea.