I have a very simple JFrame window that contains one button: 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.
I have two questions:
- Do I really need to
System.exit(0);in the above case? - If I have this
JFrameas apopupwindow, 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 mainJFramewindow? (Now I close it only bysetVisible(false);and when I do it several times through the program execution, the program turns very slow).
use
CardLayoutif is there real reason for another popup container
use
JDialogwith parent toJFrame, withsetModal/ModalityTypescreate only one JDialog and to reuse this one
JDialogbygetContentPane#removeAll()use
JOptionPanefor simple users interaction
put both together, above two points, to use
CardLayoutfor popupJDialogwith parent toJFrame, notice after switch from one card to another could be / is required to callJDialog.pack()
setVisiblewill cause slowdowndisposewill cause slowdownSystem.exitwill close entire JVM
Therefore, you should reuse a single JFrame or 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();.
Just add this: JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE).
Note: The default option for JFrame is HIDE_ON_CLOSE.
来源:https://stackoverflow.com/questions/14138499/how-to-properly-hide-a-jframe