0

I have a project that I'm working on a project that requires 2 JFrames in a single program. The problem is that when I close one the other will also close so I made a test class to see what the issue was and I still couldn't figure it out so here is the test case that I have:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class frameTest {

    public static void main(String[] args) {

        JFrame f1 = new JFrame();
        JButton open = new JButton("open");
        open.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFrame f2 = new JFrame();
                f2.setVisible(true);
                f2.setDefaultCloseOperation(f2.EXIT_ON_CLOSE);
                f2.setSize(200, 200);
            }
        });

        f1.setDefaultCloseOperation(f1.EXIT_ON_CLOSE);
        f1.setVisible(true);
        f1.setSize(500, 500);
        f1.add(open);
    }
}

When I click the open button the popup (f2) will appear but when I close it the other window will also close, why does this happen?

Krayo
  • 2,492
  • 4
  • 27
  • 45
ghost1349
  • 83
  • 1
  • 10
  • 1
    Note: [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes-good-bad-practice) – Reimeus Oct 20 '14 at 18:45

2 Answers2

3
f2.setDefaultCloseOperation(f2.EXIT_ON_CLOSE);

EXIT_ON_CLOSE means close the Java VM.

If you just want to close the current frame then use:

f2.setDefaultCloseOperation(f2.DISPOSE_ON_CLOSE);
camickr
  • 321,443
  • 19
  • 166
  • 288
  • @ghost1349, then maybe you should start "accepting" answers so everybody knows the question has been answered. – camickr Oct 21 '14 at 00:59
3

Take a look on this line:

f2.setDefaultCloseOperation(f2.EXIT_ON_CLOSE);

It means that your application is terminated when you close the frame. So, not second frame is closed. Whole application is terminated.

If you do not want this behavior remove this line.

AlexR
  • 114,158
  • 16
  • 130
  • 208