编写代码 TestKeyListener测试类
package com.xiang.lesson03;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//键盘事件
public class TestKeyListener {
public static void main(String[] args) {
new KeyFrame("键盘事件");
}
}
class KeyFrame extends Frame {
public KeyFrame(String title) {
super(title);
setVisible(true);
setBounds(2, 2, 400, 500);
addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) {
System.out.println("windowActivated");
}
@Override
public void windowClosing(WindowEvent e) {
System.out.println("windowClosing");
System.exit(0);
}
});
addKeyListener(new KeyAdapter() {
// 键盘按下
@Override
public void keyReleased(KeyEvent e) {
// 获取键盘按下的键
//获取 状态的码
int keyCode = e.getKeyCode();
System.out.println(keyCode);
if (keyCode == KeyEvent.VK_0) {
System.out.println("你按下了数字键 0 ");
}
}
});
}
}
运行结果