java 如何正确隐藏 JFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14138499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:12:20  来源:igfitidea点击:

How to properly hide a JFrame

javaswingmemory-leaksjframe

提问by Maroun

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

我有一个非常简单的JFrame窗口,其中包含一个按钮:No

In the main function I set setVisible(true);my JFrameand in the Nobutton 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.

在主函数中,我设置了setVisible(true);myJFrameNo按钮侦听器,我想关闭窗口,因此我将可见性设置为 false:setVisible(false);然后我这样做System.exit(0);是为了防止多次运行程序时可能出现的内存泄漏。

I have two questions:

我有两个问题:

  1. Do I really need to System.exit(0);in the above case?
  2. If I have this JFrameas a popupwindow, 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 JFramewindow? (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. System.exit(0);在上述情况下我真的需要吗?
  2. 如果我把它JFrame作为一个popup窗口,我真的不能使用,System.exit(0);因为这会终止整个程序。那么如何正确关闭弹出窗口并留在主JFrame窗口中呢?(现在我只关闭它setVisible(false);,当我通过程序执行多次关闭它时,程序变得非常慢)。

回答by mKorbel

  1. use CardLayout

  2. if is there real reason for another popup container

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

  1. 利用 CardLayout

  2. 如果有另一个弹出容器的真正原因

  3. 将两者放在一起,以上两点,CardLayout用于JDialog与父级的弹出窗口JFrame,注意从一张卡切换到另一张卡后可能/需要调用JDialog.pack()

回答by Doorknob

  1. setVisiblewill cause slowdown
  2. disposewill cause slowdown
  3. System.exitwill close entire JVM
  1. setVisible会导致减速
  2. dispose会导致减速
  3. System.exit将关闭整个 JVM

Therefore, you should reuse a single JFrameor JDialog.

因此,您应该重用单个JFrameJDialog.

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

在按钮的 中ActionListener,调用frame.setVisible(false);. 然后,而不是创建一个新框架,只需执行frame.setVisible(true);. 如果你想改变框架的内容,有函数frame.getContentPane().removeAll();.

回答by Hui Zheng

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

只需添加:JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)。注意:的默认选项JFrameHIDE_ON_CLOSE