concept keyCode in category java

appears as: keyCode
Swt/Jface in Action: GUI Design with Eclipse 3.0

This is an excerpt from Manning's book Swt/Jface in Action: GUI Design with Eclipse 3.0.

The following code snippet shows how to use a KeyListener to receive and process a KeyEvent. It also uses the fields (character, stateMask, and keyCode) to acquire information about the pressed key:

Button button = new Button(shell, SWT.CENTER);
button.addKeyListener(new KeyAdapter()
{
  public void keyPressed(KeyEvent e)
  {
    String string = "";
    if ((e.stateMask & SWT.ALT) != 0) string += "ALT-";
    if ((e.stateMask & SWT.CTRL) != 0) string += "CTRL-";
    if ((e.stateMask & SWT.COMMAND) != 0) string += "COMMAND-";
    if ((e.stateMask & SWT.SHIFT) != 0) string += "SHIFT-";
    switch (e.keyCode)
    {
      case SWT.BS: string += "BACKSPACE"; break;
      case SWT.CR: string += "CARRIAGE RETURN"; break;
      case SWT.DEL: string += "DELETE"; break;
      case SWT.ESC: string += "ESCAPE"; break;
      case SWT.LF: string += "LINE FEED"; break;
      case SWT.TAB: string += "TAB"; break;
      default: string += e.character; break;
    }
    System.out.println (string);
  }
});

This code uses the KeyEvent fields and the public constants to create a String that displays the name of the pressed key and any associated modifier keys. The first step in the event handler’s operation involves checking the event’s stateMask field to see whether the Alt, Ctrl, Shift, and Command keys are pressed. If so, the name of the modifier key is added to the String. The method continues by checking whether the event’s keyCode corresponds to an alphanumeric character or one of the support keys. In either case, the name of the key is appended to the String, which is sent to the console.