How to close a window without shutting down the application?

Hi,

I’m writing a program that needs multiple windows presenting information but want the user to be able to click the X and have just that window close and not the entire running program. Also, if the user clicks on a JButton like submit, then that window will close leaving the other windows open. Can someone tell me how do do this please :slight_smile:

Thanks,

Nick

On the JFrame class:


        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
               System.out.println("bye bye life");
               dispose();
            }
        });

check out JInternalFrame… basicly you add them to desktop pane as I remember and show / hide them as neccesary (you don’t have to dispose it).
… and for leaving only one window after jbutton is pressed… in actionPerformed hide all others

With Swing, your application will always continue to run unless you tell it not to. This code is what does it:


//frame is a properly created JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

If you put that code in for your main window, but do not put it on any of the other windows that you open, your application will continue to run until the main window is closed.

To close a window with a button, just call setVisible(false) on the window you want to close in the action listener for your button.

That’s excellent. Thanks guys :wink: