Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 718
BigONotation Avatar asked Nov 28 '13 10:11

BigONotation


2 Answers

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.

like image 102
kris54321 Avatar answered Nov 05 '22 22:11

kris54321


You can add a ShortcutListener to the TextArea, like this:

TextArea textArea = new TextArea();
textArea.addShortcutListener(enter);

Now you just have to initialize some ShortcutListener as follows:

ShortcutListener enter = new ShortcutListener("Enter", KeyCode.ENTER, null) {

    @Override
    public void handleAction(Object sender, Object target) {
        // Do nice stuff
        log.info("Enter pressed");
    }
};
like image 39
oburger Avatar answered Nov 05 '22 20:11

oburger