In java, how do you make only one JFrame window close when you click on x, instead of all?

0

I'm doing a Java program with multiple windows JFrame , and I wanted it to, when I pressed the x of one of the windows, it only closed, instead of all of them.

    
asked by anonymous 28.06.2015 / 03:07

2 answers

2

Just use the class constant JFrame , DISPOSE_ON_CLOSE , in the setDefaultCloseOperation(int) , instead of EXIT_ON_CLOSE . Here is a small example I wrote:

Window.java

import java.awt.BorderLayout;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class Window extends JFrame {

    private static final long serialVersionUID = 1L;
    private static final Random RND = new Random(); 
    private JPanel contentPane;

    public Window() {
        super("Close me!");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(RND.nextInt(1024), RND.nextInt(768), 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);
        setVisible(true);
    }

}

Main.java

public class Main {

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Window();
        }
    }

}
    
30.06.2015 / 23:34
1

Place in the class that extends JFrame

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    
30.06.2015 / 22:36