1

I have one window of class Jframe and it contains one button. On Clicking that button the second window of class Jframe is opened. On Clicking the close or the exit button of second window then the first window is also closed along with second window. Why is this happening?

below is my code : // this is my first file

class Frame1 extends JFrame
{
Frame1()
{
        super("hello this is window 1");
        setVisible(true);
        setSize(400,400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        JButton btn = new JButton("open second window");
       btn.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
                System.out.println("button clicked");
                Frame2 obj2 = new Frame2();
        }
    });
    add(btn);
}

public static void main(String args[])
{
        Frame1 obj = new Frame1();
}
}

// this is my second file
class Frame2 extends JFrame
{
Frame2()
{
        super("hello this is window 2");
        setVisible(true);
        setSize(400,400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
}
}
Sarthak Shah
  • 137
  • 1
  • 15

4 Answers4

2

Try changing the default close event (which quits the program) and then close that one JFrame explicitly.

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

Some links that might help:

http://tips4java.wordpress.com/2009/05/01/closing-an-application/
http://docs.oracle.com/javase/tutorial/uiswing/events/windowlistener.html
https://stackoverflow.com/a/1235283/2407870

Community
  • 1
  • 1
Chris Middleton
  • 5,654
  • 5
  • 31
  • 68
1

Change the Value of the setDefaultCloseOperation() parameter to JFrame.DO_NOTHING_ON_CLOSE to prevent the second Frame from closing the First Frame

1

Try to add window listener in the second frame, then just dispose it, something like:

frame2.addWindowListener(new java.awt.event.WindowAdapter() {
    @Override
    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
        frame2.dispose();
    }
});

OR

frame2.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);

But note that its not a good practices to use multiple JFrame's in you're application, use one JFrame and multiple Dialogs.

Salah
  • 8,567
  • 3
  • 26
  • 43
1

Remove this line from your Frame2 class

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Then add this to the same line:

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
AloneInTheDark
  • 938
  • 4
  • 15
  • 36