0

I would like to know how I could develop a Handler to manage when an user type ENTER key. For example, a login screen, you type your login and password and then you push ENTER. Is it required to add Handler in RootPanel? In a button? I do not know.

Thank you in advance for the solution.

2 Answers 2

5

I often have occasion to register a handler for enter presses, so I use the following abstract class often:

   public abstract class EnterKeyHandler implements KeyDownHandler {
    public void onKeyDown(KeyDownEvent event) {
        if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER)
            enterKeyDown(event);
    }
    public abstract void enterKeyDown(KeyDownEvent event);
    }

And then I implement it as follows by registering it with all appropriate widgets:

EnterKeyHandler doStuffHandler = new EnterKeyHandler() {
        public void enterKeyDown(KeyDownEvent event) {
        doStuff();      }
    };
    someTextBox.addKeyDownHandler(doStuffHandler );
    anotherTextBox.addKeyDownHandler(doStuffHandler );
    yetAnotherTextBox.addKeyDownHandler(doStuffHandler );

This saves you the chore of filtering out any key press that is not an enter key.

1

In the case you explained, handler should be added to TextBox since it is focused, no need to add to the RootPanel or something else. Because this event will be fired regardless its necessity when user presses Enter.

Not the answer you're looking for? Browse other questions tagged or ask your own question.