Saturday, October 1, 2011

GWT Tricks #2

I want to have a dialog box or a display on my screen where the user can just hit the "Return" key and not have to click on my OK button. It might be a data entry form and they are typing, tabbing, typing, tabbing and should not have to take their hands off the keyboard to finish...just hit Enter or Return.

To do this, you'll need to create a class for your button that listens for a Key down. Here's how:

1. First create a class that you can reuse on any form or display you like:

public class ButtonPressListener implements KeyDownHandler
{
private final Button button;

public ButtonPressListener(final Button button)
{
this.button = button;
}

@Override
public void onKeyDown(final KeyDownEvent key)
{
if (key.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER)
{
button.click();
}
}

}
This class will see a KeyDown event, check that it was the Enter key and then press your button. So if you pass in your default button or OK button, it gets activated when the user presses enter. Here's how:

First create your button -
private final Button    okButton     = new Button();
okButton.setText("OK");
Now create your listener, passing the button you want activated when the user hits Enter -
final ButtonPressListener listener = new ButtonPressListener(okButton);
Now, if your dialog box or form has other input fields, you want each of them to see an Enter key press and activate your OK button. In this example, we have a username and password field on our screen:
usernameTextBox.addKeyDownHandler(listener);
passwordTextBox.addKeyDownHandler(listener);

Now that you know how to setup a key listener, you can create all sorts of conveniences for your user and let them fly through your UI screens.

No comments:

Post a Comment