Java Swing:dispose() JFrame 不清除其控件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2037132/
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
Java Swing: dispose() a JFrame does not clear its controls
提问by Johan
I have a closeWindow() method which uses dispose() for the current JFrame to close down. When I show the window again, the controls (textboxes, lists, tables etc.) still have their previous values in place that were there when I dispose():d the frame... Why is that? Is there another way to completley close and clear a frame?
我有一个 closeWindow() 方法,它使用 dispose() 为当前 JFrame 关闭。当我再次显示窗口时,控件(文本框、列表、表格等)仍然具有它们以前的值,这些值在我 dispose():d 框架时还在那里......为什么会这样?有没有另一种方法来完全关闭和清除框架?
This is the code that another JFrame uses to show the other window, am I doing something wrong here?
这是另一个 JFrame 用来显示另一个窗口的代码,我在这里做错了吗?
@Action
public void showAddProductToOrderView() {
if (addProductToOrderView == null) addProductToOrderView = new AddProductToOrderView(this);
addProductToOrderView.setVisible(true);
}
回答by Samuel Sj?berg
Disposing a window will not clear its child text components. Dispose will release native resources. The javadoc for java.awt.Windowalso states:
处置窗口不会清除其子文本组件。Dispose 将释放原生资源。java.awt.Window的 javadoc还指出:
The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions).
通过随后调用 pack 或 show 重建本机资源,可以使 Window 及其子组件再次可显示。重新创建的 Window 及其子组件的状态将与处理 Window 时这些对象的状态相同(不考虑这些操作之间的额外修改)。
As suggested by others, create a new instance each time instead. If that's to expensive I believe your best option is to clear sub components when the view becomes visible, e.g. by overriding setVisible.
正如其他人所建议的那样,每次都创建一个新实例。如果这太昂贵,我相信您最好的选择是在视图可见时清除子组件,例如通过覆盖setVisible.
EDIT: Remove the null check to create a new frame each time.
编辑:每次删除空检查以创建一个新框架。
@Action
public void showAddProductToOrderView() {
addProductToOrderView = new AddProductToOrderView(this);
addProductToOrderView.setVisible(true);
}
I don't know about the rest of your code, if there's something else depending on the frame being reused. For example, if you have attached listeners, ensure they are unregistered to not leak them.
我不知道你的其余代码,如果还有其他东西取决于被重用的框架。例如,如果您附加了侦听器,请确保它们未注册以免泄漏。
回答by Carl Smotricz
The simplest thing to do would be to re-create the whole frame (using its constructor) before using show()to show it again. That will give you a whole new set of components, assuming that the constructor creates and places them.
最简单的做法是在再次show()显示之前重新创建整个框架(使用其构造函数)。这将为您提供一组全新的组件,假设构造函数创建并放置它们。

