8

我有一个问题,为什么在我的测试代码中没有调用“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);
    }
}
4

1 回答 1

8

setDefaultCloseOperation的默认值为HIDE_ON_CLOSE。有了这个,窗口没有关闭,它只是隐藏起来。

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

于 2012-11-07T07:21:38.500 回答