Handling enter key on Text fields

Hi how can I handle “Enter” key pressing event on a text field?

Thanks in advance

Normally you get a valuechangeevent when you deselect a field which is immediate. Enter counts as one of the things that sends this. Your field looks something like this:


TextField tf = new TextField("My textfield", valuechangelistener);
tf.setImmediate();

This way the ValueChangeListener will pick up the events.

Otherwise, you can use shortcut actions if you want something special to happen when exactly a key is pressed. You can find more of these in
the Book of Vaadin
. Short version, you do something like this.

I just thought that this handler, that submits the form on Enter key, someone may find useful:

/**
 * This action handler defines the default behaviour for "Enter" key, which submits the form.
 */
static class SubmitFormOnEnterKeyHandler implements Handler {

	private static final Action	enterKeyShortcutAction	= new ShortcutAction(null, ShortcutAction.KeyCode.ENTER, null);

	public Action[] getActions(Object target, Object sender) {
		return new Action[]{enterKeyShortcutAction};
	}

	public void handleAction(Action action, Object sender, Object target) {
		if (action == enterKeyShortcutAction) {
			// If target is a UI component, we search the form that embeds it and commit (submit) that form: 
			if (target instanceof Component) {
				Component component = (Component) target;

				while (component != null) {
					if (component instanceof Form) {
						((Form) component).commit();

						return;
					}

					// We have reached the nearest top-level container:
					if (component instanceof Window) {
						return;
					}

					component = component.getParent();
				}
			}
		}
	}
}

How about:

textField.addShortcutListener(new ShortcutListener("Shortcut Name", ShortcutAction.KeyCode.ENTER, null) {
	@Override
	public void handleAction(Object sender, Object target) {
		// your code here
	}
});

Just answering this old post to warn newbies (like me) to avoid the last suggested solution (addShortcutListener). This could make your application react weirdly as it will react to the key when you are elsewhere.

Use Dmitri suggestion instead.

M2C

My code for accepting enters as an action and limiting it to the one text field using the shortcut listener in the field factory:

public class SearchDunFieldFactory implements FormFieldFactory {

TextField searchTextField;
OuterForm outerForm;
public SearchDunFieldFactory(OuterForm outerForm) {
[indent]
super();
this.outerForm=outerForm;

 }
 @Override
 public Field createField(Item item, Object propertyId, Component component) {
     [indent]

String pid = (String) propertyId;
if (“searchField”.equals(pid)) {
[indent]
searchTextField= new TextField(“Search”,item.getItemProperty(“searchField”));
searchTextField.setWidth(“800px”);
searchTextField.addShortcutListener(new ShortcutListener(“Shortcut Name”, ShortcutAction.KeyCode.ENTER, null) {
[indent]
@Override
public void handleAction(Object sender, Object target) {
if(target==searchTextField){ //limit the enters to only from the textfield from this form factory
[indent]
// your code here
outerForm.doSearch(); //do the activity from this form button being pressed
[/indent]
}
[/indent]
}
[/indent]
});
return searchTextField;
[/indent]
}else{
[indent]
return new TextField(FormatString.formatCaption(pid),item.getItemProperty(pid));
[/indent]
}
[/indent]
}
[/indent]
}

To make it easier for newbies, use all those listeners available

private void addEnterKeyActionToTextField(final TextField textField) {
    textField.addFocusListener(new FocusListener() {
        //What will be done when your Text Field is active is Enter Key is pressed
        public void focus(final FocusEvent event) {
            //Whatever you want to do on Enter Key pressed
            // for example: saveButton.setClickShortcut(KeyCode.ENTER);
        }
    });
    textField.addBlurListener(new BlurListener() {
         // To control waht happens when your Text Field looses focus
        @Override
        public void blur(final BlurEvent event) {
            //saveButton.removeClickShortcut();
        }
    });
}

I’ve tried most of the sollutions here. Your sollution is just simple, elegant and works perfectly. Thanks for taking your time to add some thoughts to this slow discussion (5 years from the first post! :slight_smile: ) .

This can be easily achieved just by adding a shortcutlistener whenever the TextField gets the focus and removing it when it blurs. From an IOC perspective wrapping the TextField would most probably result in less rework than extending the TextField:

For example:

TextField myTextField = new TextField("A text field");
myTextField.setImmediate(true);
OnEnterKeyHandler onEnterHandler=new OnEnterKeyHandler(){
            @Override
            public void onEnterKeyPressed() {
                Notification.show("Voight Kampff Test",
                    Notification.Type.HUMANIZED_MESSAGE);
            }
        };
onEnterHandler.installOn(myTextField);

Code for OnEnterKeyHandler can be found at:

http://ramontalaverasuarez.blogspot.com/2014/06/vaadin-7-detect-enter-key-in-textfield.html

Hi Talavera Suarez Ramon David, I tried to implement a solution inspired by Yours, which haplessly does not work.

I want to create a TextArea, which comes into being after the user clicks on a table on my UI - The click triggers a valueChange, upon which the TextArea is created. I am able to create the table and I am also able to add a focus listener to the TextArea, which works fine (I checked that by adding a Notification telling me that it’s in focus). When the TextArea is in focus position, I add a ShortCutListener to it, and the task of the handleAction ought to be to check if the Action triggered by the ShortCutListener corresponds to the hitting of the ENTER key.

               final TextArea ta = new TextArea();
                                 ta.setHeight(400, UNITS_PIXELS);
                                 ta.setWidth(360, UNITS_PIXELS);
                                ta.setMaxLength(7000);//Eine Chatnachricht darf maximal 7000 Zeichen haben.        
                                ta.setImmediate(true);

                                ta.addListener(new FocusListener() {
                                ShortcutAction ent = new ShortcutAction("enter key",ShortcutAction.KeyCode.ENTER, null);    
                                 public void focus(FocusEvent event) {
                                                //Notification.show("in focus");
                                                ta.addShortcutListener(new AbstractField.FocusShortcut(ta,KeyCode.ENTER,null){
                                                        public void handleAction(ShortcutAction action,Object sender,Object target){
                                                                if(action == ent){
                                                                    Notification.show("clicked");
                                                                    }
                                                 }
                                            
                                           });
                                        }
                                   });

After all, what I want to achieve is to let the user write into my TextArea, and whenever it is in focus position (and the user subsequently is able to write to it), the hitting of the ENTER-key causes an event (which I want to check upon first of all by giving a Notification).

Sehr geehrter Herr!

It seems to me that you are not using the OnEnterKeyHandler class as stated on the tutorial. Note that it add a focus listener and a blurlistener to the component by using addFocusListener. I recommend you to refactor your code so that it uses the class, it has the advantange of being highly reusable as it may let you quickly install and uninstall the shortcut listener onto a given component.

Mit besten Grüssen empfehle ich mich.

Thank You for Your reply - Your solution works quite fine for TextField, but (if I did not commit a mistake while testing it) it is not suited for TextArea. Nonetheless, I found a workaraound. In the stead of trying to glean the KeyInput from my TextArea, I can look for ENTER’s char value, which is 10, and then I can call a Notification thereupon.

ta.addListener(new TextChangeListener() {
private static final long serialVersionUID = …

                                @Override
                                public void textChange(TextChangeEvent event) {
                                    
                                    if(event.getText().charAt(event.getText().length()-1) == 10){
                                        
                                  Notification.show("Voight Kampff Test Schluss Bunker");
                                    }
                                
                                }
                            });

TKinter: As long as I remember it does work with TextArea, but the code must be adapted (basic change).

Daniel: That will enable a global shortcut action, it will most probably not work if you need more than a single text field on the same page.

Great solution Thanks!

Thanks to all solutions. I’ve changed the code a bit to use Java 8 lambdas, perhaps someone else finds it readable too.

[code]
public final class TextFieldUtils {

/**

/**

  • Lets the ShortcutListener handle the action while the TextField has focus.
    */
    public static void handleShortcut(AbstractTextField textField, ShortcutListener shortcutListener) {
    textField.addFocusListener((FieldEvents.FocusEvent event) → textField.addShortcutListener(shortcutListener));
    textField.addBlurListener((FieldEvents.BlurEvent event) → textField.removeShortcutListener(shortcutListener));
    }

}
[/code]Usage:

    TextField searchField = new TextField();
    TextFieldUtils.handleEnter(searchField, (sender, target) -> {
      Notification.show("search: " + searchField.getValue());
    });

Thnaks Michael for the example. Should this be generalized to other components as well ? AbstractFocusables ?

I want to say thanks, even if your post was submitted over 5 years ago.

Works perfectly.

If you want to use the shortcutlistener just when textfield is focused you can do

ShortcutListener sl = new …;

textfield.addFocusListener(…){
textfield.addShortcutListener(sl);
}

textfield.addBlurListener(…){
textfield.removeShortcutListener(sl);
}

Then it is not global anymore.

Bruno Eberhard:
How about:

textField.addShortcutListener(new ShortcutListener("Shortcut Name", ShortcutAction.KeyCode.ENTER, null) {
	@Override
	public void handleAction(Object sender, Object target) {
		// your code here
	}
});

Still working in 2019