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
How to properly hide a JFrame
提问by Maroun
I have a very simple JFrame
window that contains one button: No
.
我有一个非常简单的JFrame
窗口,其中包含一个按钮: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.
在主函数中,我设置了setVisible(true);
myJFrame
和No
按钮侦听器,我想关闭窗口,因此我将可见性设置为 false:setVisible(false);
然后我这样做System.exit(0);
是为了防止多次运行程序时可能出现的内存泄漏。
I have two questions:
我有两个问题:
- Do I really need to
System.exit(0);
in the above case? - If I have this
JFrame
as apopup
window, I can't really useSystem.exit(0);
because this will terminate the whole program. So how can I properly close the popup window and stay in the mainJFrame
window? (Now I close it only bysetVisible(false);
and when I do it several times through the program execution, the program turns very slow).
System.exit(0);
在上述情况下我真的需要吗?- 如果我把它
JFrame
作为一个popup
窗口,我真的不能使用,System.exit(0);
因为这会终止整个程序。那么如何正确关闭弹出窗口并留在主JFrame
窗口中呢?(现在我只关闭它setVisible(false);
,当我通过程序执行多次关闭它时,程序变得非常慢)。
回答by mKorbel
use
CardLayout
if is there real reason for another popup container
use
JDialog
with parent toJFrame
, withsetModal
/ModalityTypes
create only one JDialog and to reuse this one
JDialog
bygetContentPane#removeAll()
use
JOptionPane
for simple users interaction
put both together, above two points, to use
CardLayout
for popupJDialog
with parent toJFrame
, notice after switch from one card to another could be / is required to callJDialog.pack()
利用
CardLayout
如果有另一个弹出容器的真正原因
使用
JOptionPane
简单的用户的交互
将两者放在一起,以上两点,
CardLayout
用于JDialog
与父级的弹出窗口JFrame
,注意从一张卡切换到另一张卡后可能/需要调用JDialog.pack()
回答by Doorknob
setVisible
will cause slowdowndispose
will cause slowdownSystem.exit
will close entire JVM
setVisible
会导致减速dispose
会导致减速System.exit
将关闭整个 JVM
Therefore, you should reuse a single JFrame
or JDialog
.
因此,您应该重用单个JFrame
或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();
.
在按钮的 中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 JFrame
is HIDE_ON_CLOSE
.
只需添加:JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)
。注意:的默认选项JFrame
是HIDE_ON_CLOSE
。