Search code examples
javagwtuibinder

In GWT is there a way to create a KeyPressEvent for the entire view instead of a single input element?


Right now I have the following code working:

@UiHandler("usernameTextBox")
void onUsernameTextBoxKeyPress(KeyPressEvent event) {
    keyPress(event);
}

@UiHandler("passwordTextBox")
void onPasswordTextBoxKeyPress(KeyPressEvent event) {
    keyPress(event);
}

void keyPress(KeyPressEvent event) {
    if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
        submit();
    }
}

I would like the ability to have just one listener for all elements on the view without duplicating an event for each textbox.

The end goal is that if they press enter, regardless of where they are on the page, it should submit the form.

Thanks!


Solution

  • I found out that the g:FocusPanel allows me to capture events for everything inside the panel.

    @UiHandler("focusPanel")
    void onFocusPanelKeyPress(KeyPressEvent event) {
        if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
            submit();
        }
    }