It is a subclass of the abstract InputEvent class and is generated when the user presses or releases a key or does both i.e. types a character.
When a key is pressed, the event generated is KEY_PRESSED
When a key is released, the event generated is KEY_RELEASED
When a character is typed on the keyboard, that is a key is pressed and then released, the event generated is KEY_TYPED
Following are the types of methods provided by KeyEvent class
int getKeyCode() It is used for getting the integer code associated with a key. It is used for KEY_PRESSED and KEY_RELEASED events. The keycodes are defined as constants in KeyEvent class
char getKeyChar() This method is used to get the Unicode character of the key pressed. It works with the KEY_TYPED events
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/* <APPLET CODE ="KeyboardEvents.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class KeyboardEvents extends Applet implements KeyListener
{
TextArea tpress,trel;
TextField t;
public void init()
{
t=new TextField(20);
t.addKeyListener(this);
tpress=new TextArea(3,70);
tpress.setEditable(false);
trel=new TextArea(3,70);
trel.setEditable(false);
add(t);
add(tpress);
add(trel);
}
public void keyTyped(KeyEvent e)
{
disppress(e,"Key Typed:");
}
public void keyPressed(KeyEvent e)
{
disppress(e,"KeyPressed:");
}
public void keyReleased(KeyEvent e)
{
String charString,keyCodeString,modString;
char c=e.getKeyChar();
int keyCode=e.getKeyCode();
int modifiers=e.getModifiers();
charString="Key character='"+c+"'";
keyCodeString="key code="+keyCode+"("+KeyEvent.getKeyText(keyCode)+")";
modString="modifiers="+modifiers;
trel.setText("Key released"+charString+keyCodeString+modString);
}
protected void disppress(KeyEvent e,String s)
{
String charString,keyCodeString,modString,tmpString;
char c=e.getKeyChar();
int keyCode=e.getKeyCode();
int modifiers=e.getModifiers();
if(Character.isISOControl(c))
{
charString="key character=(an unprintable control character)";
}
else
{
charString="key character='"+c+"'";
}
modString="modifiers="+modifiers;
tmpString=KeyEvent.getKeyModifiersText(modifiers);
if(tmpString.length()>0)
{
modString+="("+tmpString+")";
}
else
{
modString+="(no modifiers)";
}
keyCodeString="key code="+keyCode+"("+KeyEvent.getKeyText(keyCode)+")";
tpress.setText(s+charString+keyCodeString+modString);
}
}