关于Java WindowListener的问题

时间:2010-01-26 17:40:15

标签: java swing

如果您有WindowListener,那么每当窗口关闭时,windowDeactivated(WindowEvent)事件都会发生,或者windowClosing(WindowEvent)是否可能在windowDeactivated(WindowEvent)没有windowClosed(WindowEvent)的情况下发生。也就是说,窗口停用是窗口关闭的一部分吗?

最后,windowClosing(WindowEvent)总是(通常)会跟随{{1}}吗?

1 个答案:

答案 0 :(得分:7)

假设JFrame,结果似乎取决于setDefaultCloseOperation();获得WINDOW_CLOSED事件需要“在窗口上调用dispose”,例如通过DISPOSE_ON_CLOSE提及here

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** @see http://stackoverflow.com/questions/2141325 */
public class MyPanel extends JPanel {

    private static final Random RND = new Random();
    private static final WindowAdapter listener = new WindowAdapter() {

        @Override
        public void windowClosed(WindowEvent e) {
            print(e);
        }

        @Override
        public void windowClosing(WindowEvent e) {
            print(e);
        }

        @Override
        public void windowDeactivated(WindowEvent e) {
            print(e);
        }

        private void print(WindowEvent e) {
            System.out.println(e.getWindow().getName() + ":" + e);
        }
    };

    public MyPanel() {
        this.setBackground(new Color(RND.nextInt()));
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(320, 240);
    }

    private static void create() {
        for (int i = 0; i < 2; i++) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setTitle(String.valueOf(i));
            f.add(new MyPanel());
            f.addWindowListener(listener);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                create();
            }
        });
    }
}