java frame清除控件,Java Swing:dispose()JFrame不会清除其控件

这篇博客探讨了在Java中使用JFrame时遇到的问题,即关闭并重新显示窗口后,控件仍然保留之前的值。作者指出,dispose()方法并未清除组件的状态,建议每次显示新窗口时创建新的实例,或者在窗口变得可见时手动清理子组件。同时,需要注意如果存在依赖于窗口状态的其他代码,确保正确处理或解除监听器以避免内存泄漏。
摘要由CSDN通过智能技术生成

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?

This is the code that another JFrame uses to show the other window, am I doing something wrong here?

@Action

public void showAddProductToOrderView() {

if (addProductToOrderView == null) addProductToOrderView = new AddProductToOrderView(this);

addProductToOrderView.setVisible(true);

}

解决方案

Disposing a window will not clear its child text components. Dispose will release native resources. The javadoc for java.awt.Window also states:

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

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值