//主程序类
public class KeyPress extends JFrame {
public static void main(String[] args) {
KeyFrame frame = new KeyFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
//面板设置类
class KeyFrame extends JFrame {
public KeyFrame() {
setTitle("KeyPress");
setSize(WIDTH, HEIGHT);
// 将panel加入到frame
KeyPanel panel = new KeyPanel();
Container contentPane = getContentPane();
contentPane.add(panel);
}
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
}
//底层类
class KeyPanel extends JPanel implements KeyListener {
public KeyPanel() {
addKeyListener(this);
} // 注册监听器
public boolean isFocusTraversable() {
return true;
}// 允许面板获得焦点
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (KeyVirtualCode == -1) // 输出虚拟键码
g.drawString("虚拟键码:", 100, 80);
else
g.drawString("虚拟键码:" + KeyVirtualCode, 100, 80);
g.drawString("键名称:" + KeyText, 100, 110);// 输出键的名称
g.drawString("字符:" + KeyChar, 100, 140); // 输出字符
}
public void keyPressed(KeyEvent event) // 得到虚拟键码
{
KeyVirtualCode = event.getKeyCode();
}
public void keyReleased(KeyEvent event) {
KeyVirtualCode = event.getKeyCode(); // 得到键的名称
KeyText = event.getKeyText(KeyVirtualCode);
if (!isChar) {
KeyChar = ' ';
}
isChar = false;
repaint();
}
public void keyTyped(KeyEvent event) // 得到字符
{
KeyChar = event.getKeyChar();
isChar = true;
}
public char KeyChar = ' ';
public int KeyVirtualCode = -1;
public String KeyText = "";
public boolean isChar = false;
}