JFrame怎么监听和处理各种窗口事件
时间: 2024-06-01 19:09:34 浏览: 185
JFrame可以监听和处理各种窗口事件,包括:
窗口打开事件:当窗口被打开时触发。
窗口关闭事件:当窗口被关闭时触发。
窗口激活事件:当窗口被激活时触发。
窗口失去焦点事件:当窗口失去焦点时触发。
窗口最小化事件:当窗口被最小化时触发。
窗口最大化事件:当窗口被最大化时触发。
窗口大小改变事件:当窗口的大小改变时触发。
窗口位置改变事件:当窗口的位置改变时触发。
窗口图标改变事件:当窗口的图标改变时触发。
可以通过实现JFrame的WindowListener接口来监听和处理这些事件。具体实现方法如下:
- 实现WindowListener接口:
public class MyFrame extends JFrame implements WindowListener {
// 实现接口方法
}
- 注册事件监听器:
MyFrame frame = new MyFrame(); frame.addWindowListener(this); // 注册事件监听器
- 处理事件:
public void windowOpened(WindowEvent e) { // 处理窗口打开事件 }
public void windowClosing(WindowEvent e) { // 处理窗口关闭事件 }
// 其他事件处理方法
完整代码示例:
import java.awt.; import java.awt.event.; import javax.swing.*;
public class MyFrame extends JFrame implements WindowListener {
public MyFrame() {
setTitle("JFrame事件监听");
setSize(300, 200);
setLocationRelativeTo(null);
addWindowListener(this); // 注册事件监听器
setVisible(true);
}
public void windowOpened(WindowEvent e) {
System.out.println("窗口打开事件");
}
public void windowClosing(WindowEvent e) {
System.out.println("窗口关闭事件");
dispose(); // 关闭窗口
}
public void windowClosed(WindowEvent e) {
System.out.println("窗口关闭完成事件");
}
public void windowActivated(WindowEvent e) {
System.out.println("窗口激活事件");
}
public void windowDeactivated(WindowEvent e) {
System.out.println("窗口失去焦点事件");
}
public void windowIconified(WindowEvent e) {
System.out.println("窗口最小化事件");
}
public void windowDeiconified(WindowEvent e) {
System.out.println("窗口最大化事件");
}
public void windowStateChanged(WindowEvent e) {
System.out.println("窗口状态改变事件");
}
public static void main(String[] args) {
new MyFrame();
}
}
相关推荐



















