How to remove all components from a JFrame in Java?

给你一囗甜甜゛ 提交于 2019-11-27 01:30:19

问题


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?


回答1:


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.




回答2:


getContentPane().removeAll();
getContentPane().repaint();



回答3:


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(new component);
validate();


来源:https://stackoverflow.com/questions/9347076/how-to-remove-all-components-from-a-jframe-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!