Java Swing: dispose () JFrame does not clear its controls

I have a closeWindow () method that uses dispose () for the current JFrame to close. When I show the window again, the controls (text fields, lists, tables, etc.) still have their previous values, which were there when I positioned (): d frame ... Why? Is there any other way to complete and clear the frame?

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

@Action public void showAddProductToOrderView() { if (addProductToOrderView == null) addProductToOrderView = new AddProductToOrderView(this); addProductToOrderView.setVisible(true); } 
+4
source share
2 answers

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

A window and its subcomponents can be displayed again by restoring their own resources and then calling pack or show. The status of the updated window and its subcomponents will be identical to the states of these objects at the point where the Window was located (not taking into account additional changes between these actions).

As suggested by others, create a new instance each time instead. If it's expensive, I think your best option is to clear the subcomponents when the view becomes visible, for example. by overriding setVisible .

EDIT: Remove the zero 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 is anything else depending on which frame is being reused. For example, if you connected listeners, make sure they are unregistered so as not to miss them.

+5
source

The simplest task would be to recreate the entire frame (using its constructor) before using show() to show it again. This will give you a whole new set of components, assuming the constructor creates and places them.

+3
source

All Articles