java中如何处理JFrame窗口事件?

这个例子告诉你如何处理JFrame窗口事件,如windowOpened,windowClosing,windowClosed,等处理这些事件,我们需要一个添加WindowListener监听器JFrame实例。在这里,我们使用WindowAdapter抽象类并实现要处理的事件的方法。

package org.nhooo.example.swing;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class WindowListenerDemo extends JFrame {
    public WindowListenerDemo() {
        initializeComponent();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new WindowListenerDemo().setVisible(true));
    }

    private void initializeComponent() {
        setSize(300, 300);
        setTitle("Window Listener");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        this.addWindowListener(new WindowAdapter() {
            // 打开窗口时调用。
            public void windowOpened(WindowEvent e) {
                System.out.println("Window Opened Event");
            }

            // 在关闭窗口的过程中调用。
            // 此时关闭操作可以被覆盖。
            public void windowClosing(WindowEvent e) {
                System.out.println("Window Closing Event");
            }

            // 窗口关闭时调用。
            public void windowClosed(WindowEvent e) {
                System.out.println("Window Close Event");
            }

            // 当窗口被图标化时调用。
            public void windowIconified(WindowEvent e) {
                System.out.println("Window Iconified Event");
            }

            // 取消图标化窗口时调用。
            public void windowDeiconified(WindowEvent e) {
                System.out.println("Window Deiconified Event");
            }

            // 激活窗口时调用。
            public void windowActivated(WindowEvent e) {
                System.out.println("Window Activated Event");
            }

            // 禁用窗口时调用。
            public void windowDeactivated(WindowEvent e) {
                System.out.println("Window Deactivated Event");
            }

            // 更改窗口状态时调用。
            public void windowStateChanged(WindowEvent e) {
                System.out.println("Window State Changed Event");
            }

            // 当“窗口”设置为焦点窗口时调用,这意味着
            // 窗口或其子组件之一将接收键盘
            // 事件。
            public void windowGainedFocus(WindowEvent e) {
                System.out.println("Window Gained Focus Event");
            }

            // 当窗口不再是焦点窗口时调用
            // 该键盘事件将不再传递到窗口或任何
            // 它的子组件。
            public void windowLostFocus(WindowEvent e) {
                System.out.println("Window Lost Focus Event");
            }
        });
    }
}