Java GUI之KeyListener

Java GUI之KeyListener,用于键盘监听事件,继承自EventListener,可以监听键盘按键的按下,释放等操作。
如下是KeyListen接口的定义:
public interface KeyListener extends EventListener {

    /**
     * Invoked when a key has been typed.
     * See the class description for {@link KeyEvent} for a definition of
     * a key typed event.
     */
    public void keyTyped(KeyEvent e);

    /**
     * Invoked when a key has been pressed.
     * See the class description for {@link KeyEvent} for a definition of
     * a key pressed event.
     */
    public void keyPressed(KeyEvent e);

    /**
     * Invoked when a key has been released.
     * See the class description for {@link KeyEvent} for a definition of
     * a key released event.
     */
    public void keyReleased(KeyEvent e);
}
public class KeyBoardListen extends JFrame {
   /**
    * 
    */
   private static final long serialVersionUID = 1L;
   private String s = null;
   private JLabel label;

   KeyBoardListen() {
      setLayout(new FlowLayout());
      label = new JLabel();
      addKeyListener(new KeyListener() {
         @Override
         public void keyTyped(KeyEvent e) {
            // TODO Auto-generated method stub
            s = "按下的键是Type" + e.getKeyChar();
            label.setText(s);
            System.out.println(s);
         }

         @Override
         public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub
            s = "释放的键是:" + e.getKeyChar();
            label.setText(s);
            System.out.println(s);
         }

         @Override
         public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub
            s = "按下的键是Press" + e.getKeyChar();
            label.setText(s);
            System.out.println(s);
         }
      });
      add(label);
      setBounds(350, 100, 600, 500);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }

   public static void main(String[] args) {
      new KeyBoardListen();
   }
}
源码地址:https://github.com/followwwind/javase
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值