How to properly hide a JFrame

2019-04-29 09:43发布

问题:

I have a very simple JFrame window that contains one button: No.

In the main function I set setVisible(true); my JFrame and in the No button listener I want to close the window so I set the visibility to false: setVisible(false); and after that I do System.exit(0); in order to prevent possible memory leaks when running the program many times.

I have two questions:

  1. Do I really need to System.exit(0); in the above case?
  2. If I have this JFrame as a popup window, I can't really use System.exit(0); because this will terminate the whole program. So how can I properly close the popup window and stay in the main JFrame window? (Now I close it only by setVisible(false); and when I do it several times through the program execution, the program turns very slow).

回答1:

  1. use CardLayout

  2. if is there real reason for another popup container

    • use JDialog with parent to JFrame, with setModal / ModalityTypes

    • create only one JDialog and to reuse this one JDialog by getContentPane#removeAll()

    • use JOptionPane for simple users interaction

  3. put both together, above two points, to use CardLayout for popup JDialog with parent to JFrame, notice after switch from one card to another could be / is required to call JDialog.pack()



回答2:

  1. setVisible will cause slowdown
  2. dispose will cause slowdown
  3. System.exit will close entire JVM

Therefore, you should reuse a single JFrame or JDialog.

In the button's ActionListener, invoke frame.setVisible(false);. Then instead of creating a new frame just do frame.setVisible(true);. If you want to change the contents of the frame, there is the function frame.getContentPane().removeAll();.



回答3:

Just add this: JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE). Note: The default option for JFrame is HIDE_ON_CLOSE.