KeyListener Example

KeyListener Example


After seeing the low-level events handling with MouseListener and MouseMotionListener, let us go to the actions of keyboard.

Keyboard actions are handled by KeyListener. Keyboard generates KeyEvent. Three types of actions can be done with keyboard – by pressing the key, by releasing the key and typing the key. These actions are represented by three abstract methods of KeyListener. In the following KeyListener Example, an appropriate message is displayed at the DOS prompt as per the key typed on the keyboard.

KeyListener Example

KeyListener Example

Output screen of KeyListener Example

getKeyChar() is an important method of KeyEvent class that returns the key typed by the user as a char value. Using this char, the programmer can handle the events differently the way he would like. As a practice, the frame is closed with anonymous inner class of WindowAdapter.

Leave a Reply

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