How to properly hide a JFrame

2019-04-29 09:23发布

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).

3条回答
够拽才男人
2楼-- · 2019-04-29 09:41
  1. use CardLayout

  2. if is there real reason for another popup container

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

查看更多
在下西门庆
3楼-- · 2019-04-29 09:41
  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();.

查看更多
霸刀☆藐视天下
4楼-- · 2019-04-29 09:49

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

查看更多
登录 后发表回答