Monday, July 27, 2009

KeyPressEvent: Getting the key code

There is a new way to get what keys are pressed in GWT 1.6. Now KeyPressHandler is used to listen to a TextBox:

TextBox box = new TextBox();
box.addKeyPressHandler(new KeyPressHandler()
{
public void onKeyPress(KeyPressEvent event)
{
// Listen to key event
}
});


You can use event.getCharCode() to get the character that was pressed, but in order to get the key code (int) that was pressed you need to use the following method:

event.getNativeEvent().getKeyCode()


So here is code to listen to when the "Enter" key is pressed:

TextBox box = new TextBox();
box.addKeyPressHandler(new KeyPressHandler()
{
public void onKeyPress(KeyPressEvent event)
{
if (KeyCodes.KEY_ENTER == event.getNativeEvent().getKeyCode())
{
System.out.println("Enter key has been pressed");
}
}
});