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
import java.awt.*;
import java.awt.event.*;

public class KeyDemo extends Frame implements KeyListener  
{                       
  public KeyDemo()
  {
    addKeyListener(this);                   // link the frame with KL
                                            // window closing
    addWindowListener(new WindowAdapter()
    {
      public void windowClosing(WindowEvent e)
      {   
        System.exit(0);    
      }  
    } 
    );

    setSize(300,300);
    setVisible(true);
  }                                         // close constructor
                                            // override the 3 abstract methods of KL
  public void keyPressed(KeyEvent e) {  }   // give empty implementation if you would not like any action
  public void keyReleased(KeyEvent e) { }
  public void keyTyped(KeyEvent e)
  {
    char ch = e.getKeyChar();  
    if(ch == 'r' || ch == 'R')              // if r or R is typed
    {
      setBackground(Color.red);
    }
    else if(ch == 'b'|| ch == 'B')     // if b or B is typed
    {
      setBackground(Color.blue);
    }
    else if(ch == 'y'|| ch == 'Y')    // if y or Y is typed
    {
      setBackground(Color.yellow);
    }
    else if(ch == 'a'|| ch == 'A')    // if a or A is typed
    {
      System.out.println("Good afternoon");
    }
    else if(ch == 'm'|| ch == 'M')      // if m or M is typed
    {
      System.out.println("Good Morning");
    }
    else 
    {
      System.out.println("You typed " + ch + " but type r, b, y, a and m only");
    }
  }
  public static void main(String snrao[])
  {
    new KeyDemo();
  }                      
}                        
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 Comment

Your email address will not be published.