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

3

5

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!

Winy answered 8/3, 2012 at 14:54 Comment(0)
W
1

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();
    }
}
Winy answered 20/3, 2012 at 21:10 Comment(0)
B
7

What works, but still requires you to specify it for each widget, but doesn't require duplicate code:

@UiHandler({"usernameTextBox", "passwordTextBox"})
void onPasswordTextBoxKeyPress(KeyPressEvent event) {
    keyPress(event);
}
Britton answered 8/3, 2012 at 15:27 Comment(0)
S
2

Yes jackcrews is correct. Also you can try the following. It may be VerticalPanel, DockLayoutPanel etc....

UiBinder.ui.xml

<gwt:VerticalPanel ui:field="mainPanel">
    <gwt:Label>Name</gwt:TextBox>
    <gwt:TextBox ui:field="textBox">
</gwt:VerticalPanel>

Main.java

@UiField
VerticalPanel mainPanel;

public Main() {
  focushandler();
}

void focusHandler() { 
    mainPanel.addDomHandler(new Handler(), KeyPressEvent.getType());
}

final class Handler implements KeyPressHandler {

    @Override
    public void onKeyPress(KeyPressEvent event) {
        //Code what you expect
    }
}

Actually this has more number of lines. But it is good practice.

Regards, Gnik

Sherlocke answered 19/4, 2012 at 10:29 Comment(0)
W
1

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();
    }
}
Winy answered 20/3, 2012 at 21:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.