java 键盘监听

 1 package LoginDemo;
 2 
 3 import java.awt.event.KeyEvent;
 4 import java.awt.event.KeyListener;
 5 import java.awt.event.WindowEvent;
 6 import java.awt.event.WindowAdapter;
 7 import javax.swing.JFrame;
 8 import javax.swing.JScrollPane;
 9 import javax.swing.JTextArea;
10 
11 class MyKeyHandle extends JFrame implements KeyListener{
12     private JTextArea text=new JTextArea();
13     public MyKeyHandle(){
14         super.setTitle("Welcome!");
15         JScrollPane scr=new JScrollPane(text);
16         scr.setBounds(5, 5, 300, 200);
17         super.add(scr);
18         text.addKeyListener(this);
19         super.setSize(310,210);
20         super.setVisible(true);
21         super.addWindowListener(new WindowAdapter(){
22             public void windowClosing(WindowEvent arg0){
23                 System.exit(1);
24             }
25         });
26     }
27     @Override
28     public void keyTyped(KeyEvent e) {
29         text.append("输入的内容是:"+e.getKeyChar()+"\n");
30         
31     }
32     @Override
33     public void keyPressed(KeyEvent e) {
34         text.append("键盘“"+KeyEvent.getKeyText(e.getKeyCode())+"”键按下\n"); 
35         
36     }
37     @Override
38     public void keyReleased(KeyEvent e) {
39         // TODO Auto-generated method stub
40         text.append("键盘“"+KeyEvent.getKeyText(e.getKeyCode())+"”键松开\n");
41     }
42 }
43 public class MyKeyEventDemo {
44     public static void main(String[] args) {
45         
46         new MyKeyHandle();
47     }
48 }

 

你可能感兴趣的:(Java基础)