// program that trace the key pressed and released
Description
The KeyListener class in Java is used to trace the key Pressed, Released and Typed. The class which uses key listener should implement KeyListener class. It contains three methods they are:
- keyPressed()
- keyReleased()
- KeyTyped()
When a key is pressed the KeyPressed() method will be invoked, when a key is released the KeyReleased() method will be invoked and when a key is typed the KeyTyped() method will be invoked. The KeyListener class requires that all these three methods be defined in the class which implements it.
Program
import java.awt.*;
import java.awt.event.*;
public class KeyTrace extends Frame implements KeyListener
{
Label l;
public KeyTrace(String s)
{
super(s);
l=new Label("Key Listener");
add(l);
addKeyListener(this);
setSize(200,200);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}});
}
public void keyPressed(KeyEvent e)
{
l.setText("KeyPresed is "+e.getKeyChar());
}
public void keyReleased(KeyEvent e)
{
l.setText(e.getKeyChar()+" is Released");
}
public void keyTyped(KeyEvent e)
{
l.setText("You Typed "+e.getKeyChar());
}
public static void main(String s[])
{
new KeyTrace("Key Listener Example....!");
}
}
Output
KeyListener in Java |