Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire a (KEY_ENTER) key press event in GWT

Tags:

gwt

What I'm trying to do is fire an enter key press event in GWT. This is my keyhandler:

    itemBox.addKeyDownHandler(new KeyDownHandler() { 
          public void onKeyDown(KeyDownEvent event) {
                 if(event.getNativeKeyCode == KeyCodes.KEY_ENTER) {
                       // do something
                 }

Then later I wanna fire an enter key press event but I can't seem to figure out how I do this. I wanna do something like KeyDownEvent.setNativeKeyCode(KEY_ENTER).

     textBox.fireEvent(new KeyDownEvent(null));

Is it possible to set these parameters?

like image 200
Justin K Avatar asked Oct 23 '12 07:10

Justin K


People also ask

How do you key press an event?

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt , Shift , Ctrl , or Meta .

Which event is called when key is pressed?

The keydown event is fired when a key is pressed. Unlike the deprecated keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

How can I listen for keypress event on the whole page?

If you want to perform any event on any specific keyboard button press, in that case, you can use @HostListener. For this, you have to import HostListener in your component ts file. import { HostListener } from '@angular/core'; then use below function anywhere in your component ts file.


1 Answers

You can fire the event using DomEvent.fireNativeEvent, instead of textBox.fireEvent.

Here is a working example how to do this:

final TextBox tb = new TextBox();
tb.addKeyDownHandler(new KeyDownHandler() {

    @Override
    public void onKeyDown(KeyDownEvent event) {
     if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
                 Window.alert("enter!");
           }
    }
});

Button b = new Button("keyevent");
b.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
    DomEvent.fireNativeEvent(Document.get().createKeyDownEvent(false, false, false, false, KeyCodes.KEY_ENTER), tb);
    }
});

RootPanel.get().add(tb);
RootPanel.get().add(b);
like image 120
tommueller Avatar answered Nov 03 '22 02:11

tommueller