2

I have a class like this:

public class A {
    public static void main() {
        B f1 = new B();
        f1.setVisible(true);
    }

    class B extends JFrame {
        public B() {
            JButton btn = new JButton("click me");
            btn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    C f2 = new C();
                    f2.setVisible(true);
                }
            });
            add(btn);
        }
    }

    class C extends JFrame {
        public C() {
            //whatever here
        }
    }
}

When I first run this java code, a window X contains a button "click me". After I click it, another new window Y is popped out. But the problem is that when I close the new window Y, the old window X is closed together with Y automatically. (i.e. they are closed at the same time)

What I wanna do is that after I close Y, X keeps there and not to be closed. How to do it?

mKorbel
  • 109,107
  • 18
  • 130
  • 305
sc1013
  • 1,005
  • 2
  • 16
  • 23
  • 1
    You would change the argument of the `setDefaultCloseOperation()` method, which defines what happens when the close button is clicked. In this case, you would use `DISPOSE_ON_CLOSE` as the argument. The reason both frames are being disposed is because you set the argument to `EXIT_ON_CLOSE`, which terminates the *entire process*. If you need further assistance, please ask. :) – fireshadow52 May 08 '12 at 14:07
  • Normally closing one window won't affect the other window. Could it be that you are setting the defaultCloseOperation to Exit? – ControlAltDel May 08 '12 at 14:07
  • @fireshadow52 YEAH! I got it! Thank you! – sc1013 May 08 '12 at 14:10
  • See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/a/9554657/418556) – Andrew Thompson May 08 '12 at 14:10
  • @Steven Happy to help :) – fireshadow52 May 08 '12 at 14:12

3 Answers3

3

Simplest way, put this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE) in the second window constructor.

Other ways: http://www.leepoint.net/notes-java/GUI/containers/10windows/12frameclose.html

CosminO
  • 4,802
  • 6
  • 26
  • 48
2

You would change the argument of the setDefaultCloseOperation() method, which defines what happens when the close button is clicked. In this case, you would use DISPOSE_ON_CLOSE as the argument. The reason both frames are being disposed is presumably because you set the argument to EXIT_ON_CLOSE (if you didn't set this explicitly, then it was done for you; it is the default close behavior for all frames) which terminates the entire process—this includes all open windows and frames. If you need further assistance, please ask. :)

fireshadow52
  • 5,888
  • 2
  • 29
  • 45
0

What DefaultCloseOperation has Y Frame ? It is probably EXIT_ON_CLOSE, thus X is closed together with Y. Change it to DISPOSE_ON_CLOSE or leave default value. It should work.

KrHubert
  • 1,020
  • 7
  • 17