Java 实现输入键盘上任意键显示出相对应的ASCII

//主程序类

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值