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.
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.
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();
}
}
}
Place in the class that extends JFrame
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);