← prev
Tóm Tắt
Java KeyListener Interface
The Java KeyListener is notified whenever you change the state of key. It is notified against KeyEvent. The KeyListener interface is found in java.awt.event package, and it has three methods.
Interface declaration
Following is the declaration for java.awt.event.KeyListener interface:
Methods of KeyListener interface
The signature of 3 methods found in KeyListener interface are given below:
Sr. no.
Method name
Description
1.
public abstract void keyPressed (KeyEvent e);
It is invoked when a key has been pressed.
2.
public abstract void keyReleased (KeyEvent e);
It is invoked when a key has been released.
3.
public abstract void keyTyped (KeyEvent e);
It is invoked when a key has been typed.
Methods inherited
This interface inherits methods from the following interface:
- java.awt.EventListener
Java KeyListener Example
In the following example, we are implementing the methods of the KeyListener interface.
KeyListenerExample.java
Output:
Java KeyListener Example 2: Count Words & Characters
In the following example, we are printing the count of words and characters of the string. Here, the string is fetched from the TextArea and uses the KeyReleased() method of KeyListener interface.
KeyListenerExample2.java
Output:
Next Topic
Java WindowListener
← prev
next →