package three.day.frame;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class KeyEventDemo extends JFrame implements KeyListener
{
private JLabel lbClickKey;
private JLabel lbTip;
private JTextField tfClickKey;
private JTextArea tfTip;
public KeyEventDemo(String title) throws HeadlessException {
super(title);
Container panel = getContentPane();
panel.setLayout(new GridLayout(2,2));
lbClickKey = new JLabel("请按键盘");
lbTip = new JLabel("结果");
tfClickKey = new JTextField(20);
tfTip = new JTextArea(20,50);
tfTip.setBorder(BorderFactory.createEmptyBorder());
tfTip.setOpaque(true);
tfTip.setBackground(new Color(180,255,0));
panel.add(lbClickKey);
panel.add(tfClickKey);
panel.add(lbTip);
panel.add(tfTip);
setBounds(300,200,500,400);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
tfClickKey.addKeyListener(this);
}
public static void main(String[] args) {
new KeyEventDemo("KeyEvent Demo");
}
@Override
public void keyPressed(KeyEvent e) {
lbTip.setText("键盘按下着呢");
}
@Override
public void keyReleased(KeyEvent e) {
lbTip.setText("键盘松开了");
}
@Override
public void keyTyped(KeyEvent e) {
lbTip.setText("键盘按下了");
tfTip.append(String.valueOf(e.getKeyChar()));
}
}