KeyAdapter and KeyEvent Simple Example

KeyAdapter and KeyEvent Simple Example


Java permits to handle low-level events of mouse and keyboard. For keyboard the java.awt.event package comes with KeyListener and KeyAdapter.

KeyAdapter is an abstract class that replaces the usage of KeyListener. Instead of implementing KeyListener and overriding its 3 abstract methods, we can as well extend KeyAdapter and override the interested abstract methods – may be one or two. Adapter classes, introduced from JDK 1.1, are elaborately discussed in Java AWT Adapters with Listener Vs Corresponding Adapter.

Following is a simple KeyAdapter KeyEvent Example of what user typed on the frame is displayed at DOS prompt.

File Name: FrameKeyAdapterDemo.java

As FrameKeyAdapterDemo is already extending Frame, it is not possible to extend further KeyAdapter. This is the problem of not supporting multiple inheritance. To overcome this, a convenient class Helper is created extending KeyAdapter.

Now we have two classes FrameKeyAdapterDemo and Helper not involved in inheritance. It is necessary to link these two classes as FrameKeyAdapterDemo is having frame and Helper is having even handler, KeyAdapter. Linking involves small logic. See next.

Helper h1 = new Helper();
addKeyListener(h1);

General way of adding the listener is addKeyListener(this). But here is small difference. A Helper object is created and passed as addKeyListener(h1). This is how the two classes linked here.

Observe only one method is overridden of keyTyped() and not the remaining two of keyPressed() and keyReleased(). This is the advantage of KeyAdapter over KeyListener.

char char1 = e.getKeyChar();

An important method of KeyEvent is getKeyChar() that returns the key typed by the user on the frame as a char data type.

KeyAdapter KeyEvent Example
Output screen when some keys from keyboard are typed of KeyAdapter KeyEvent Example

Leave a Reply

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