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.
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.
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");
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With