Kane Williamson
Kane Williamson

Reputation: 11

JFrame: All the frames close when I try to close just one of them

public class Scratch {
    public static void main(String[] args) {
        Dimension d = new Dimension(300,300);
        JFrame frame1 = new JFrame("Frame-1");
        JFrame frame2 = new JFrame("Frame-2");
        frame1.setSize(250,250);
        frame2.setSize(d);
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame1.setVisible(true);
        frame2.setVisible(true);
    }
}

When I run this, the two frames show up as expected, but when I close one of them, both of them close. I want to achieve the functionality where only the frame I click 'x' on closes and the other remains open until I click the 'x' on it. How do I do it?

Upvotes: 1

Views: 1718

Answers (2)

camickr
camickr

Reputation: 324098

    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

The "EXIT" tells the JVM to stop so all the windows are closed:

So you could be using:

    frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

Then only the frame you click on will close. When both frames are closed the JVM will exit.

However, that is not a good solution. An application should generally only have a single JFrame and then use a JDialog for a child window. Using this approach the code would be:

JDialog dialog = new JDialog(frame1);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

Depending on you requirement you would make the dialog modal or non-modal.

Using this approach the JVM will exit when you close the frame however it will stay open when you close a child dialog.

Read this forum question about multiple JFrames: The Use of Multiple JFrames: Good or Bad Practice?. It will give more thoughts on why using 2 JFrames is not a good idea.

Upvotes: 4

Kumaresan Perumal
Kumaresan Perumal

Reputation: 1956

public class Scratch {
    public static void main(String[] args) {
        Dimension d = new Dimension(300,300);
        JFrame frame1 = new JFrame("Frame-1");
        JFrame frame2 = new JFrame("Frame-2");
        frame1.setSize(250,250);
        frame2.setSize(d);
        frame1.setVisible(true);
        frame2.setVisible(true);
    }
}

you add one of them to your frame.

setVisible(false);
dispose(); 
setDefaultCloseOperation(DISPOSE_ON_CLOSE);

Upvotes: 0

Related Questions