// MasterProgramClass
Public class keypress extends jframe {
Public static void main (string [] ARGs ){
Keyframe frame = new keyframe ();
Frame. setdefaclocloseoperation (jframe. exit_on_close );
Frame. setvisible (true );
}
}
// Panel setting class
Class keyframe extends jframe {
Public keyframe (){
Settitle ("keypress ");
Setsize (width, height );
// Add the panel to the frame
Keypanel Panel = new keypanel ();
Container contentpane = getcontentpane ();
Contentpane. Add (panel );
}
Public static finals int width = 300;
Public static final int size = 200;
}
// Underlying class
Class keypanel extends jpanel implements keylistener {
Public keypanel (){
Addkeylistener (this );
} // Register the listener
Public Boolean isfocustraversable (){
Return true;
} // Allows the Panel to focus
Public void paintcomponent (Graphics g ){
Super. paintcomponent (g );
If (keyvirtualcode =-1) // output the virtual key code
G. drawstring ("virtual keycode:", 100, 80 );
Else
G. drawstring ("virtual key code:" + keyvirtualcode, 100, 80 );
G. drawstring ("key name:" + keytext, 100,110); // name of the output key
G. drawstring ("character:" + keychar, 100,140); // output character
}
Public void keypressed (keyevent event) // obtain the virtual key code
{
Keyvirtualcode = event. getkeycode ();
}
Public void keyreleased (keyevent event ){
Keyvirtualcode = event. getkeycode (); // obtain the key name.
Keytext = event. getkeytext (keyvirtualcode );
If (! Ischar ){
Keychar = '';
}
Ischar = false;
Repaint ();
}
Public void keytyped (keyevent event) // get the character
{
Keychar = event. getkeychar ();
Ischar = true;
}
Public char keychar = '';
Public int keyvirtualcode =-1;
Public String keytext = "";
Public Boolean ischar = false;
}