简体   繁体   中英

How to close JFrame?

I have the main application frame. If user clicks the button he gets a new frame which has some chart in it. Now if I want to close that chart both chart and main application closes. How can I distinguish those two closings. Certainly I don't want my application to be closed after closing the frame in which I put chart. Here's the code of the chart frame.

chartBttn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                final ShowChart sc = new ShowChart("Reserve Selection", getUtilExperiments() );
                sc.pack();
                RefineryUtilities.centerFrameOnScreen(sc);
                sc.setVisible(true);
                sc.setDefaultCloseOperation(ShowChart.DISPOSE_ON_CLOSE);

            }
        });

You can use the dispose() method. Or you can call setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); on the JFrame.

If I understood you correctly on your new JFrame build a method for your close button or X window button with:

setVisible(false); 
dispose();

Otherwise please post your code on creating the new JFrame etc.

Certainly I don't want my application to be closed after closing the frame in which I put chart.

1) don't create lots of JFrames on the fly, create JFrame only once and re-use that for next usage(s), then

  • call only for visibility setVisible(false/true) with setDefaultCloseOperation(JFrame.NOTHING_ON_CLOSE)

or very simple workaround

  • setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)

2) or JDialog with setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE)

3) NOTICE: but in this case isn't possible close the current JVM instance, you have to add JButton or JMenu/JMenuItem which accelerate for System.exit(1)

simply use super.dispose(); for closing previous jframe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM