KeyAdapter Example getKeyChar() getKeyCode()

KeyAdapter Example getKeyChar() getKeyCode()


Note 1: Before going into this notes, if not aware of about adapter classes, It is advised to go through Java AWT Adapters.

Note 2: For notes on integration of classes (it is done here also), refer Applet: MouseMotionAdapter getX() and getY() Example .

Two methods getKeyChar() and getKeyCode() of KeyEvent class are used in this program. Let us see what Java Designer says about these methods.

  1. char getKeyChar(): Returns the character associated with the key in this event. For example, the KEY_TYPED event for shift + "a" returns the value for "A".
  2. int getKeyCode(): Returns the integer keyCode associated with the key in this event.

Note: getKeyCode() returns an integer value of the keyboard key as defined in the underlying OS, but not ASCII value.

KeyAdapter Example

Following are the two programs (HTML and Applet) involved.

HTML file to run applet

Applet File Name: AppletKeyAdapterExample.java

case KeyEvent.VK_F1:

VK_F1 represents an integer number defined in java.awt.event.KeyEvent class that represents F1 functional key. KeyEvent class provides key codes upto F24.

addKeyListener(new HelperClass(this));

The above statement is explained (comes under integration of classes) in Applet: MouseMotionAdapter getX() and getY() Example.

In keyTyped() and keyReleased() methods getKeyCode() does not work and use only getKeyChar(). In these two methods, the getKeyCode() is VK_UNDEFINED.

For numbers it is VK_1 or VK_2 etc. The other virtual keys are VK_INSERT, VK_LESS, VK_RIGHT_PARENTHESIS, VK_WINDOWS etc. For a list of virtual and other keys refer Java API, KeyEvent class.


KeyAdapter Example
Output screen when F3 is pressed KeyAdapter Example

One thought on “KeyAdapter Example getKeyChar() getKeyCode()

Leave a Reply

Your email address will not be published. Required fields are marked *