public class Keyboard extends JFrame implements KeyListener{ JLabel I; Keyboard(String name){ super(name); init(); } public void init(){ Toolkit tk = getToolkit(); Dimension dm = tk.getScreenSize(); setLocation((int)(dm.getWidth()-getWidth())/2,(int)(dm.getHeight()-getHeight())/2); JPanel pan = new JPanel(); pan.setBackground(Color.YELLOW); pan.setLayout(new FlowLayout(FlowLayout.CENTER)); I = new JLabel(); I.setText("键盘事件处理"); pan.add(I); this.add(pan); this.addKeyListener(this); } //敲击 public void keyTyped(KeyEvent e){ } //按下 public void keyPressed(KeyEvent e){ I.setText("你刚才敲的字母是"+e.getKeyCode()+" " + e.getKeyChar()); } //释放 public void keyReleased(KeyEvent e){ I.setText("key up"); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Keyboard f = new Keyboard("test"); f.pack(); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }