0

Let's suppose two JDialogs, j1 and j2, and I need j2 to be closed when I hit the "X" button on the j1.

I tried to implement WindowListener on j1, and I used j2.dispose() in the windowClosing() and the windowClosed() methods but it didn't work.

Is it possible to put an actionPerformed on the "X" button for example? or is it possible to do it using a windowListener and how?

Thank you in advance.

splungebob
  • 5,357
  • 2
  • 22
  • 45
user3610008
  • 79
  • 2
  • 11
  • Maybe [this post](http://stackoverflow.com/questions/7652821/java-listener-on-dialog-close) can help. – BlackDwarf Sep 12 '14 at 20:23
  • 1
    `I tried to implement WindowListener on j1, and I used j2.dispose() in the windowClosing() and the windowClosed() methods but it didn't work.` That is the correct approach. The code should be implemented in windowClosing(). If you need more help (after reading the suggestions already given) then post your [SSCCE](http://sscce.org/) demonstrating the problem. – camickr Sep 12 '14 at 20:42

2 Answers2

3

My guess is you forgot to add your WindowListener. Put a System.out.println in your WindowListener methods to see if they're actually being called.

Here's a working example of what you describe:

public class Test {

    public static void main(String[] args) {
        final JDialog jd1 = new JDialog((JFrame) null, "Dialog 1", false);
        jd1.setVisible(true);

        JDialog jd2 = new JDialog((JFrame) null, "Dialog 2", false);
        jd2.setVisible(true);
        jd2.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent we) {
                jd1.dispose();
            }
        });
    }
}
martinez314
  • 12,162
  • 5
  • 36
  • 63
2

Is it possible to put an actionPerformed on the "X" button for example?

Check out my answer in this posting: Associate predefined action to close button Java JDialog

Community
  • 1
  • 1
camickr
  • 321,443
  • 19
  • 166
  • 288
  • I guess your solution works two, thank you for it, and i will keep it in mind in case i'd need it in the future. But for now i will use Whiskeyspider's solution since it's less complicated. – user3610008 Sep 12 '14 at 20:53