javaswingjdialogwindowlistener

JDialog WindowOpened event is fired just once


I'm trying to get the WindowOpened event from JDialog, but it is fired just once. Why windowClosing works correctly and WindowOpened just once? Is there any way to fire the open event for JDialog every time?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;

public class NewClass extends JDialog {

    public void init() {
        setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        setModal(true);
        setSize(100,100);
        setLocationRelativeTo(null);
    }

    public void addListener() {
        addWindowListener(
            new java.awt.event.WindowAdapter() {
            public void windowOpened(WindowEvent e) {
                System.out.println("Invoking WindowOpened from JDialog");
            }
            public void windowClosing(WindowEvent e) {
                System.out.println("Invoking WindowClosing from JDialog");
                dispose();
            }
        });
    }

    public static void main( String args[]) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(200,70);

        final NewClass d = new NewClass();
        d.init();
        d.addListener();

        JButton b = new JButton("Show Dialog");
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                d.setVisible(true);
            }
        });

        f.getContentPane().add(b);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
}

Solution

  • addWindowListener(new WindowAdapter() {
                @Override
                public void windowActivated(WindowEvent e) {
                    // TODO Auto-generated method stub
                    super.windowActivated(e);
                }
            });