Question

I use GWT-Ext library for building GUI for a webapp. I'd like to process an ENTER key press inside of the NumberField.

It should be like this:

    final NumberField requiredHeight = new NumberField();
    requiredHeight.setValue(125);
    requiredHeight.setAllowBlank(false);
    requiredHeight.setAllowNegative(false);
    requiredHeight.setAllowDecimals(false);
    KeyListener listener = new KeyListener() {

        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode()==13)
                addPortlet(requiredHeight.getValue().intValue());
        }

    };
    requiredHeight.addKeyListener(listener);

But the code doesn't do anything! What am I doing wrong? Generally speaking, what is the best way to add such a handler to the field?

Was it helpful?

Solution

OK, solved that at last. There is another callback function inside of KeyListener - componentKeyPress instead of keyPressed. This is the correct code:

    KeyListener listener = new KeyListener() {
        @Override
        public void componentKeyPress(ComponentEvent event) {
            if(event.getKeyCode()==13)
            {
                addPortlet(requiredHeight.getValue().intValue());
            }
            super.componentKeyPress(event);
        }

    };
    requiredHeight.addKeyListener(listener);

OTHER TIPS

Some methods are deprecated, I use following code on my simple login form:

    KeyDownHandler handler = new KeyDownHandler() {

        @Override
        public void onKeyDown(KeyDownEvent event) {
            if (event.getNativeKeyCode() == 13) {
                btnLogin.click(); 
            }
        }
    };
    tbLogin.addKeyDownHandler(handler);
    tbPassword.addKeyDownHandler(handler);

Registering a key listener in fact registers the listener to 3 different events: key-up, key-down and key-press, two of which are completely pointless in your case.

A more compact solution would be the usage of a generic listener, as follows:
(pardon me for using an anonymous listener class, it is quicker yet evidently has the same effect)

import com.extjs.gxt.ui.client.event.Events; 

requiredHeight.addListener(Events.OnKeyPress, new Listener<ComponentEvent>() {
    @Override
    public void handleEvent(ComponentEvent e) {
        if (e.getKeyCode()==13)
            addPortlet(requiredHeight.getValue().intValue());           
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top