Java KeyListener

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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. It has three methods.

Methods of KeyListener interface

The signature of 3 methods found in KeyListener interface is given below:

  1. public abstract void keyPressed(KeyEvent e);  
  2. public abstract void keyReleased(KeyEvent e);  
  3. public abstract void keyTyped(KeyEvent e);  

Java KeyListener Example

  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. public class KeyListenerExample extends Frame implements KeyListener{  
  4.     Label l;  
  5.     TextArea area;  
  6.     KeyListenerExample(){  
  7.           
  8.         l=new Label();  
  9.         l.setBounds(20,50,100,20);  
  10.         area=new TextArea();  
  11.         area.setBounds(20,80,300300);  
  12.         area.addKeyListener(this);  
  13.           
  14.         add(l);add(area);  
  15.         setSize(400,400);  
  16.         setLayout(null);  
  17.         setVisible(true);  
  18.     }  
  19.     public void keyPressed(KeyEvent e) {  
  20.         l.setText("Key Pressed");  
  21.     }  
  22.     public void keyReleased(KeyEvent e) {  
  23.         l.setText("Key Released");  
  24.     }  
  25.     public void keyTyped(KeyEvent e) {  
  26.         l.setText("Key Typed");  
  27.     }  
  28.   
  29.     public static void main(String[] args) {  
  30.         new KeyListenerExample();  
  31.     }  
  32. }  

Output:

java awt keylistener example 1

Java KeyListener Example 2: Count Words & Characters

  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. public class KeyListenerExample extends Frame implements KeyListener{  
  4.     Label l;  
  5.     TextArea area;  
  6.     KeyListenerExample(){  
  7.           
  8.         l=new Label();  
  9.         l.setBounds(20,50,200,20);  
  10.         area=new TextArea();  
  11.         area.setBounds(20,80,300300);  
  12.         area.addKeyListener(this);  
  13.           
  14.         add(l);add(area);  
  15.         setSize(400,400);  
  16.         setLayout(null);  
  17.         setVisible(true);  
  18.     }  
  19.     public void keyPressed(KeyEvent e) {}  
  20.     public void keyReleased(KeyEvent e) {  
  21.         String text=area.getText();  
  22.         String words[]=text.split("\s");  
  23.         l.setText("Words: "+words.length+" Characters:"+text.length());  
  24.     }  
  25.     public void keyTyped(KeyEvent e) {}  
  26.   
  27.     public static void main(String[] args) {  
  28.         new KeyListenerExample();  
  29.     }  
  30. }  

Output:

java awt keylistener example 2