4

I was going through the tutorial available on GWT website for StockWatcher application and testing the application as described in Step4: Manage Events on the Client.

Below piece of code behaves differently in Firefox and IE7. In IE7 this works well, i.e. If I enter some junk characters in Text field and hit Enter "event.getCharCode() == KeyCodes.KEY_ENTER" line gets executed successfully and I could see an alert message. However this same line does not work, if I use Firefox.

When I use Firefox and press Enter, event.getCharCode returns some junk character. What am I doing wrong here? or is this expected behavior?

newSymbolTextBox.addKeyPressHandler(new KeyPressHandler() {
          public void onKeyPress(KeyPressEvent event) {
            if (event.getCharCode() == KeyCodes.KEY_ENTER) {
              addStock();
            }
          }
        });
Vicky
  • 5,380
  • 18
  • 60
  • 83

1 Answers1

9

Use a KeyUpHandler instead of a KeyPressHandler to catch non-character keys (like enter, escape, etc.). Call KeyUpEvent#getNativeKeyCode() to get the key code.

Jason Terk
  • 6,005
  • 1
  • 27
  • 31
  • If I replace KeyPressHandler with KeyUphandler, how will I retrieve the character code in case of KeyUpHandler? The KeyUpEvent does not have getCharCode(). – Vicky Apr 07 '11 at 01:48
  • Ok I got that working by using event.getNativeKeyCode() method to get the character code associated with event. However, why KeyUpHandler works in this case and not KeyPressHandler? – Vicky Apr 07 '11 at 01:56
  • 1
    KeyPress is for key presses that result in actual character input. KeyUp and KeyDown also include non-printing keys. – Jason Terk Apr 07 '11 at 16:17