Java enables any key on the input keyboard to display the corresponding ASCII

Source: Internet
Author: User

// 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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.