Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly hide a JFrame

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:

  1. Do I really need to System.exit(0); in the above case?
  2. If I have this JFrame as a popup window, I can't really use System.exit(0); because this will terminate the whole program. So how can I properly close the popup window and stay in the main JFrame window? (Now I close it only by setVisible(false); and when I do it several times through the program execution, the program turns very slow).
like image 554
Maroun Avatar asked Jan 03 '13 11:01

Maroun


People also ask

How do you hide a frame window?

Use a Valance or Cornice Box To hide the uppermost portion of the ugly window frame, install a valance on a separate rod from the rest of the curtains to maintain the ability to move the panels as needed, or install a cornice box.

How do you hide a frame window in Java?

For hiding a JFrame, setVisible(false) is correct (and again besides the deprecated hide() again the only way). Depending on if you plan to eventually reuse the frame (show it again in future) you may additionally want to additionally call dispose() if you will not show the frame again.

What does JFrame setVisible do?

The setSize(400,300) method of JFrame makes the rectangular area 400 pixels wide by 300 pixels high. The default size of a frame is 0 by 0 pixels. The setVisible(true) method makes the frame appear on the screen.

How do you hide labels in Java?

setText("") will make a label invisible so long as it has no icon.


2 Answers

  1. use CardLayout

  2. if is there real reason for another popup container

    • use JDialog with parent to JFrame, with setModal / ModalityTypes

    • create only one JDialog and to reuse this one JDialog by getContentPane#removeAll()

    • use JOptionPane for simple users interaction

  3. put both together, above two points, to use CardLayout for popup JDialog with parent to JFrame, notice after switch from one card to another could be / is required to call JDialog.pack()

like image 112
mKorbel Avatar answered Sep 28 '22 07:09

mKorbel


  1. setVisible will cause slowdown
  2. dispose will cause slowdown
  3. System.exit will 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();.

like image 43
tckmn Avatar answered Sep 28 '22 06:09

tckmn