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
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).
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 interactionput 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()
setVisible
will cause slowdowndispose
will cause slowdownSystem.exit
will close entire JVMTherefore, you should reuse a single
JFrame
orJDialog
.In the button's
ActionListener
, invokeframe.setVisible(false);
. Then instead of creating a new frame just doframe.setVisible(true);
. If you want to change the contents of the frame, there is the functionframe.getContentPane().removeAll();
.Just add this:
JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)
. Note: The default option forJFrame
isHIDE_ON_CLOSE
.