Frage

My goal is to activate button's onClick(..) method if I press Enter key (KEY_ENTER) on the keyboard. For this purpose I am trying the following code but I am getting an exception which says:

com.google.gwt.event.shared.UmbrellaException: Exception caught: com.google.gwt.user.client.ui.Button cannot be cast to com.google.gwt.event.dom.client.ClickHandler

Code:

returnKeyHandler = new KeyDownHandler() {

        @Override
        public void onKeyDown(KeyDownEvent event) {
            if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
                Window.alert("Enter key pressed!!");
                ((ClickHandler) button).onClick(null);
            }
        }
    };

    Button button = new Button();
    button.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {

            Window.alert("blah blah");
            //blah blah..

        }
    });

    TextBox textBox = new TextBox();
    textBox.addKeyDownHandler(returnKeyHandler);

I can understand the exception but unable to find the solution.

War es hilfreich?

Lösung

If it's a GWT Button just call:

button.click();

see: http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/Button.html#click()

but if not and if you don't need do nothing else in java, you can call native method in JS:

private native void click(Element button)/*-{
    button.click(); //or jQuery: $(button).click();
}-*/;

If you need use Java code check this:

call click() function as programmatically in GWT

Andere Tipps

How about creating a new function called say doXYZ() and have the functionality to be implemented by the button ClickHandler as well as on the KeyPressHandler in this function itself and then invoke this doXYZ() method from both places?

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top