In java, how to make only one Jframe window close when clicking on the x instead of all?

Asked

Viewed 671 times

0

I’m making a program in Java with multiple windows JFrame, and wanted that when I pressed the x of one of the windows only this one closed, instead of all of them.

  • 4

    Consider including what you are trying to do. In addition, perhaps the best, in your case, is not to use multiple JFrame, but use JInternalFrame.

2 answers

2

Just use the class constant Jframe, DISPOSE_ON_CLOSE, in the method setDefaultCloseOperation(int), instead of EXIT_ON_CLOSE. Here’s a little example I worked out:

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();
        }
    }

}

1

Put in the class that extends Jframe

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.