如何从 Java 中的 JFrame 中删除所有组件?
我正在编写一个程序,其中有一个 JFrame,我想从中删除所有组件,然后仅向其中添加一个组件并重新绘制框架。到目前为止,我所拥有的类似于下面的代码(在实现 JFrame 的对象中调用,其中 StartPanel 实现 JPanel):
removeAll();
startPanel = new StartPanel();
startPanel.setVisible(true);
add(startPanel);
revalidate();
repaint();
但是,当我运行代码时,它显示一个空窗口(不是 startPanel),当我最小化/调整窗口大小时窗口,窗口变黑。如果我省略了 removeAll()
并且 JFrame 上已经没有元素,它会很好地显示 startPanel。关于如何实际删除所有内容,然后让新面板仍然显示的任何想法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须调用
尚未被覆盖为
add()
或remove()
的removeAll()
才能转发到contentPane
根据需要。You must call
removeAll()
has not been overridden asadd()
orremove()
to forward to thecontentPane
as necessary.假设您的目标是在之后添加其他内容
您清除了应该在之后调用验证的框架
添加这些组件来更新它
assuming your goal is to add something else after
you clear the frame you should call validate after
adding thoes components to update it