窗体监听事件WindowListener

本文详细介绍了Java Swing中EXIT_ON_CLOSE与DISPOSE_ON_CLOSE的区别及使用场景,通过具体示例展示了两种关闭方式的行为差异,并解释了WindowListener接口中各方法的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

EXIT_ON_CLOSE:结束窗口所在的应用程序。在窗口被关闭的时候会退出JVM。

DISPOSE_ON_CLOSE:隐藏当前窗口,并释放此窗体占有的资源。如果程序没有其他线程在运行,当所有窗口都被dispose后,JVM也会退出。

举例说明:关闭窗体A,窗体B也会退出。关闭窗体B,窗体A不会退出。

public class Demo{
    public static void main(String[] args){
        JFrame window1=new JFrame("窗体A");
        JFrame window2=new JFrame("窗体B");
        window1.setBounds(100,100,200,100);
        window2.setBounds(400,100,200,100);
        window1.setVisible(true);
        window2.setVisible(true);
        window1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        window2.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    }
}
【窗体监听事件 WindowListener】
windowOpened 打开
windowActivated 激活(获得焦点状态)
windowDeactivated 非激活(失去焦点状态)
windowIconified 最小化
windowDeiconified 最小化恢复正常
windowClosing 关闭(右上角X),优先于windowClosed
windowClosed 关闭,DISPOSE_ON_CLOSE时才会被调用
public class Demo extends JFrame {
    public Demo() {
        setBounds(100, 100, 300, 300);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setVisible(true);
        addWindowListener(new MyWindowListener());//调用方法类对象
    }

    class MyWindowListener implements WindowListener {
        public void windowOpened(WindowEvent e) {
            System.out.println("窗体打开");
        }

        public void windowClosing(WindowEvent e) {
            System.out.println("窗体关闭exit");
        }

        public void windowClosed(WindowEvent e) {
            System.out.println("窗体关闭dispose");
        }

        public void windowIconified(WindowEvent e) {
            System.out.println("窗体最小化");
        }

        public void windowDeiconified(WindowEvent e) {
            System.out.println("窗体最小化恢复正常");
        }

        public void windowActivated(WindowEvent e) {
            System.out.println("窗体激活");
        }
        
        public void windowDeactivated(WindowEvent e) {
            System.out.println("窗体非激活");
        }
    }

    public static void main(String[] args) {
        new Demo();
    }
}

 

转载于:https://www.cnblogs.com/xixixing/p/9492594.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值