Java/GWT/KeyboardListener

Материал из Java эксперт
Перейти к: навигация, поиск

Listen to enter key pressed event

package com.jexp.gwt.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.KeyboardListenerAdapter;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class GWTClient implements EntryPoint{
  Button button = new Button("Login");
  public void onModuleLoad() {
    final Label loginPrompt = new Label("Please Log In");
    final Grid grid = new Grid(3, 2);
    final Label namePrompt = new Label("Name");
    final TextBox nameTextbox = new TextBox();
    final Label passwordPrompt = new Label("Password:");
    final PasswordTextBox passwordTextbox =
        new PasswordTextBox();
    RootPanel.get().clear();
    loginPrompt.addStyleName("loginPrompt");
    nameTextbox.addStyleName("nameField");
    passwordTextbox.addStyleName("passwordField");
    button.addClickListener(new ClickListener() {
      public void onClick(Widget sender) {
        Window.alert("Button clicked");
      }
    });
    SubmitListener sl = new SubmitListener();
    passwordTextbox.addKeyboardListener(sl);
    nameTextbox.addKeyboardListener(sl);
    grid.setWidget(0, 0, namePrompt);
    grid.setWidget(0, 1, nameTextbox);
    grid.setWidget(1, 0, passwordPrompt);
    grid.setWidget(1, 1, passwordTextbox);
    grid.setWidget(2, 1, button);
    RootPanel.get().add(loginPrompt);
    RootPanel.get().add(grid);
  }
  private class SubmitListener extends KeyboardListenerAdapter {
    public void onKeyPress(Widget sender, char key, int mods) {
      if (KeyboardListener.KEY_ENTER == key)
        button.click();
    }
  }
}