Keyboard Input KeyEvent KeyListener Example Applet


We have seen earlier to handle the mouse stable and mouse movement events with Applet. Now let us see with keyboard. A similar program is available with frame.

In this simple KeyListener Example, depending on the key typed by the user, the words are displayed in the applet window. getKeyChar() of KeyEvent returns the key typed as a character.

KeyListener Example as Applet

Following is the HTML file to run the applet

HTML file to run the applet


 

Applet Program: AppletKeyListener.java

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

public class AppletKeyListener extends Applet implements KeyListener
{
  char ch;
  String str;
  public void init()            // link the KeyListener with Applet
  {
    addKeyListener(this);
  }
  			        // override all the 3 abstract methods of KeyListener interface 
  public void keyPressed(KeyEvent e)   {   }
  public void keyReleased(KeyEvent e)  {   }
  public void keyTyped(KeyEvent e)  
  {   
    ch = e.getKeyChar();
    if(ch == 'a')
      str = "a for apple";    
    else if(ch == 'e')
      str = "e for elephant";    
    else if(ch == 'i')
      str = "i for igloo";    
    else if(ch == 'o')
      str = "o for ox";    
    else if(ch == 'u')
      str = "u for umbrella";    
    else
      str = "Type only vowels a, e, i, o, u only";    
  
    repaint();
  }    

  public void paint(Graphics g)
  {
    g.drawString(str, 100, 150);
    showStatus("You typed " + ch + " character");
  }
}

ch = e.getKeyChar();

Of all the code, this is an important method. The getKeyChar() method of KeyEvent returns the key typed by the user as a character. This character is used as a handle to do some functionality in the code.

showStatus(“You typed ” + ch + ” character”);

showStatus(String message) method of Applet class displays the message on the status bar of applet window. Observe, the output screen.


ima
Output screen when letter ‘u’ typed of KeyListener Example