Soren Johnson
Soren Johnson

Reputation: 2611

Is there a way to trap a keyboard event in GWT?

I'm trying to trap key downs in GWT, and I've tried both addKeyDownHandler and onBrowserEvent. The problem is that they work as long as the appropriate widget had the focus, but it stops working when something else has the focus. I could add the code to every single widget, but that seems crazy. I also tried forcing one single widget to always have the focus, but that causes other problems with things like TextBoxes (which need the focus for typing).

Is there just a simple, high-level way to trigger some code when a key is pressed in GWT, regardless of which widget has the focus?

Upvotes: 4

Views: 3912

Answers (2)

Thomas Broyer
Thomas Broyer

Reputation: 64541

You can use either Event.addNativePreviewHandler, or a KeyDownHandler that you'd attach to RootPanel.get() (using addDomHandler: RootPanel.get().addDomHandler(myHandler, KeyDownEvent.getType())), depending on whether you want to listen in the capture or bubble phase (the capture phase is emulated in IE).

Upvotes: 8

Zasz
Zasz

Reputation: 12538

Why don't you add the keyDownHandler to the body element like this and add the handler to that? All javascript events will bubble down unless you prevent it in a function().

Example :

RootPanel.getBodyElement()

Then wrap into a class to make it a Widget and addDomHandler like described here. Or if this proves not very straightforward, then simply write as javascript in the hosted page, or use native methods(GWT allows you to write javascript using native keyword).

Upvotes: 0

Related Questions