Java Tutorial Key Event, Keyboard Input and KeyListener

Java Tutorial Key Event, Keyboard Input and KeyListener

Keyboard generate KeyEvent and handled by KeyListener overriding 3 abstract methods. Example given with Screenshot where key typed is displayed in TextField.

Every component either software (like button) or hardware (like keyboard or mouse) when interacted by the user generates an event. The events can be categorized into two – Semantic and Low-level.
Semantic events are generated by software components and low-level events are generated by hardware components.

To handle low-level events, the java.awt.event package comes with three listeners – MouseListener (with 3 abstract methods), MouseMotionListener (with 2 abstract methods) and KeyListener (with 3 abstract methods). This posting shows how to handle the key events generated by the Keyboard keys with KeyListener.

The KeyListener interface comes with three abstract methods.

public abstract void keyPressed(KeyEvent);
public abstract void keyReleased(KeyEvent);
public abstract void keyTyped(KeyEvent);

The first one keyPressed() is called when a key on the keyboard is pressed and second one keyReleased() is called when the key is released and the last one keyTyped() is called when a key is typed.

In the following program, the key typed by the user is displayed in a text field.

The TextField object tf is created and added to south of the frame. The key typed by the user on the keyboard is displayed in the text field.

addKeyListener(this);

This method registers (or links) the frame with KeyListener. Else, the events will not be handled by the KeyListener.

setFocusable(true);

The cursor focus will be in the frame. If not given, the cursor focus will be in text field.

The three abstract methods of KeyListener are overridden. The first two are given empty body and the key events are handled in keyTyped() method.

char ch = e.getKeyChar();

The getKeyChar() method of KeyEvent class returns the key typed by the user as a char data type. This char is displayed in the text field.

Output screen


KeyListener

View All for Mouse Listener/Adapter, Mouse Motion Listener/Adapter, Key Listener/Adapter

Leave a Reply

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