1. JavaGUI编程之窗口监听事件和键盘监听事件(AWT)
1.1 窗口监听事件:
示例代码:
package GUI.TestWindow;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestWindow {
public static void main(String[] args) {
new WindowFrame();
}
}
class WindowFrame extends Frame {
public WindowFrame() throws HeadlessException {
setBackground(Color.ORANGE);
setBounds(100, 100, 400, 300);
setVisible(true);
addWindowListener(new WindowAdapter() {
// 关闭窗口
@Override
public void windowClosing(WindowEvent e) {
System.out.println("windowClosing");
setVisible(false);// 隐藏窗口
System.exit(0);// 关闭窗口
}
// 激活窗口
@Override
public void windowActivated(WindowEvent e) {
WindowFrame windowFrame = (WindowFrame) e.getSource();
windowFrame.setTitle("被激活了");//把窗口的title设置为"被激活了"
System.out.println("windowActivated");
}
});
}
}
运行结果:
1.2 键盘监听
示例代码:
package GUI.TestKey;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class TestKeyListener {
public static void main(String[] args) {
new KeyFrame();
}
}
class KeyFrame extends Frame {
public KeyFrame() throws HeadlessException {
setBounds(100, 100, 200, 100);
setVisible(true);
addKeyListener(new KeyAdapter() {
// 键盘按下
@Override
public void keyPressed(KeyEvent e) {
// 获得键盘按下的键是哪一个 你可以自己去根据按下的键设置相应的事件
System.out.println(e.getKeyChar());
}
});
}
}