我有一个问题,为什么在我的测试代码中未按以下方式调用“windowClosed”方法,

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

public class Tmp {

    class TFrame extends JFrame{
        private static final long serialVersionUID = -5729542298504858399L;

        public TFrame() {
            setTitle("title");
            setSize(300, 300);
        }
    }


    public static void main(String[] args) {
        final TFrame t = new Tmp().new TFrame();
        t.addWindowStateListener(new WindowAdapter() {
            @Override
            public void windowStateChanged(WindowEvent e) {
                super.windowStateChanged(e);
                System.out.println(e.getOldState() + "<-old new->" + e.getNewState());
            }
        });
        t.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosed(WindowEvent e) {
                super.windowClosed(e);
                System.out.println(e.getID() + "closed " + e.getNewState());
            }

            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                System.out.println(e.getID() + "closing" + e.getNewState());
            }
        });
        t.setVisible(true);
    }
}

如果我写语句setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)或显式调用dispose()到TFrame,则将调用windowClosed()。

有没有人可以更详细地解释它,让我困惑的是为windowClosed()编写监听器的属性方式是什么,谢谢。

//////////////////根据Dan的一些指南进行更新////////////////
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Tmp {

    class TFrame extends JFrame {
        // ignored .....
        t.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosed(WindowEvent e) {
                super.windowClosed(e);
                System.out.println(e.getID() + "closed " + e.getNewState());
            }

            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                System.out.println(e.getID() + "closing" + e.getNewState());
                int quit = JOptionPane.showConfirmDialog(t, "Are you sure to quit?");
                if(quit == JOptionPane.YES_OPTION){
                    t.dispose();
                }
                else if (quit == JOptionPane.NO_OPTION){
                    t.setVisible(false);
                }
            }
        });
        t.setVisible(true);
        t.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    }
}

最佳答案

setDefaultCloseOperation的默认值为HIDE_ON_CLOSE。这样,窗口不会关闭,而是仅隐藏。

将值更改为其他值,您实际上将其关闭而不是仅将其隐藏,因此将触发该事件。

关于java - 为什么不关闭windowClosed?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13264907/

10-10 04:06