views:

52

answers:

1

If you have a WindowListener, will a windowDeactivated(WindowEvent) event always occur whenever a window is closed, or is it possible for a windowClosing(WindowEvent) to occur without a windowDeactivated(WindowEvent) occurring. That is, is window deactivation a part of window closing?

Finally, will a windowClosed(WindowEvent) always (normally) follow a windowClosing(WindowEvent)?

+1  A: 

Assuming JFrame, the result seems to depend on the setDefaultCloseOperation(); getting a WINDOW_CLOSED event requires "calling dispose on the window", e.g. via DISPOSE_ON_CLOSE, as mentioned 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;

public class MyPanel extends JPanel {

    private static final Random RND = new Random();

    public MyPanel() {
        this.setPreferredSize(new Dimension(320, 240));
        this.setBackground(new Color(RND.nextInt()));
    }

    private static void create() {
        for (int i = 0; i < 2; i++) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            MyPanel p = new MyPanel();
            f.add(p);
            f.setTitle(String.valueOf(i));
            f.pack();
            f.setVisible(true);
            f.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosed(WindowEvent e) {
                    print(e);
                }

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

                @Override
                public void windowDeactivated(WindowEvent e) {
                    System.out.println(e);
                }

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

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                create();
            }
        });
    }
}
trashgod