简体   繁体   中英

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!

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);
}

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

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM