How to remove all components from a JFrame in Java?
Asked Answered
H

3

33

I'm writing a program where I have a JFrame and I want to remove all components from it, then add just one component to it and repaint the frame. What I have so far is something like the code below (called in an object that implements JFrame, where StartPanel implements JPanel):

removeAll();    
startPanel = new StartPanel();
startPanel.setVisible(true);
add(startPanel);
revalidate();
repaint();

However, when I run the code it shows an empty window (not the startPanel) and when I minimize/resize the window, the window turns black. If I leave out the removeAll() and there are not elements already on the JFrame it displays the startPanel just fine. Any ideas on how to actually remove everything, and then get the new panel to still show up?

Harville answered 19/2, 2012 at 5:46 Comment(2)
One word: CardLayoutSain
@HovercraftFullOfEels that might work, but is there some other way to do it manually? and why isn't removeAll() working as I think it should? what if in other parts of the code I need to have some combinations of different components (not just one showing at a time), so I don't want a CardLayout?Harville
B
59

You must call

 private JFrame frame = new JFrame();
 ...
 ...
 frame.getContentPane().removeAll();
 frame.repaint();

removeAll() has not been overridden as add() or remove() to forward to the contentPane as necessary.

Bilbe answered 19/2, 2012 at 6:42 Comment(3)
@scae: Kavka appears to have the sharper eyes than the rest of us. Good catch and 1+.Sain
Thank you for your concise and helpful answer. removeAll() really should have been overridden like add() and remove() the way you described. Just another one of Java's odd quirks...Canon
A call to revalidate() may also be necessary just as shown in the original question, but not in this answer. Calling revalidate() is necessary if you later add something else to the JFrame. I know this isn't the original question, but I believe it is a common enough use case to note it here. As it was my use case and I found this question/answer in my Google search.Scabies
T
6

assuming your goal is to add something else after you clear the frame you should call validate after adding thoes components to update it

getContentPane().removeAll();
add(/*a new component*/);
validate();
Trimurti answered 27/8, 2015 at 15:27 Comment(0)
C
5
getContentPane().removeAll();
getContentPane().repaint();
Consuela answered 18/12, 2013 at 10:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.