2

I have a Jframe window inside which there is a button. By clicking the button it opens a new JFrame window. But when I close this window it automatically closes the first Jframe window with the button. How can I prevent the first Jframe window from closing when I close the second?

public static void main (String[] args){
        JFrame frame = new JFrame("Test");
        frame.setVisible(true);
        frame.setSize(500,500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton button = new JButton("Test");


        button.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                new SView().gui();
            }
        });


        JPanel panel = new JPanel();
        GridBagLayout gridbag = new GridBagLayout();
        panel.setLayout(gridbag);
        panel.add(button);
        panel.setBackground(new Color(156, 93, 82));
        frame.add(panel, BorderLayout.CENTER);
Umzz Mo
  • 219
  • 1
  • 6
  • 14
  • 1
    JFrames weren't made for doing this but rather to hold a single stable GUI. Also don't go swapping JFrames as that makes for a very bad user experience. You're much better off swapping views via a CardLayout or if you must show a dependent dialog window, then using a JDialog or JOptionPane. – Hovercraft Full Of Eels May 04 '12 at 23:08
  • I wish, but If I start changing around then its gonna get very messy. So is there not a way of preventing it then? – Umzz Mo May 04 '12 at 23:10
  • 1
    See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/a/9554657/418556) for more tips. *"If I start changing around then its gonna get very messy."* Don't worry. It is already ***very messy.*** – Andrew Thompson May 04 '12 at 23:28

1 Answers1

3

Don't call

 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Garrett Hall
  • 29,524
  • 10
  • 61
  • 76