KeyListener is generally used with Text related components like TextField, TextArea, etc.

KeyListener Interface

As per the event delegation model we are going to implement this interface in our class. KeyListener consists of 3 methods which are as below.

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

To add KeyListener on any component/applet the syntax is: textObj.addKeyListener(this);
For further reference you can refer my article on Event Handling Methodologies.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class AppletKeyEvents extends Applet implements KeyListener
	Label l1, l2;
	TextField tf;
	TextArea ta;
	public void init() 
		l1 = new Label("Enter Text:");
		l2 = new Label("Output:");
		ta = new TextArea(7,50);
		tf = new TextField(20);
	public void keyTyped ( KeyEvent e )
  		ta.append("Key Typed: " + tf.getText()+"\n");
    public void keyPressed ( KeyEvent e)
  		ta.append ( "Key Pressed: "+ tf.getText() +"\n") ; 
 	public void keyReleased ( KeyEvent e )
  		ta.append( "Key Released: "+ tf.getText()+"\n" ) ; 

<applet code="AppletKeyEvents" width="500" height="300"></applet>