3

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.

Shobhit
  • 407
  • 5
  • 15
  • how about if you just call the `click` method of that button directly on your `keypress`? `button.click()` – vvns Aug 02 '13 at 09:47

2 Answers2

3

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

Community
  • 1
  • 1
Mateusz
  • 1,222
  • 11
  • 22
  • I agree with this answer. Using `Button.click()` instead of your current `((ClickHandler) button).onClick(null);` will do what you need. – Churro Aug 02 '13 at 21:14
1

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?

kedar
  • 103
  • 1
  • 11
  • I have already thought about this alternate solution but that's not what I want. Thanks for the suggestion. – Shobhit Aug 05 '13 at 08:05