public static void main(String[] args) {
new KeyListenerDemo();
}
private Frame f;
private TextField tf;
private Button but;
KeyListenerDemo() {
init();
}
private void init() {
f = new Frame("myFrame");
f.setBounds(300, 250, 400, 250);
f.setLayout(new FlowLayout());
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
tf = new TextField(25);
but = new Button("button");
myEvent_1();
myEvent_2();
f.add(tf);
f.add(but);
f.setVisible(true);
}
private void myEvent_2() {
but.addMouseListener(new MouseAdapter() {
int count = 0;
@Override
public void mouseClicked(MouseEvent e) {
e.getClickCount();
tf.setText(String.valueOf(count++));
}
});
}
private void myEvent_1() {
tf.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();//返回与键关联的整数
if (!(code >= KeyEvent.VK_0 && code <= KeyEvent.VK_9))
e.consume();//不执行事件源代码
if (e.getKeyCode() == KeyEvent.VK_ENTER && e.isControlDown())
System.out.println("run run");
//getkeyText(code)返回与该code关联的字符,如code为65,则返回A
System.out.println(KeyEvent.getKeyText(code) + "..." + code);
}
});
}