如何从 Java 中的 JFrame 中删除所有组件?

发布于 2025-01-07 16:57:47 字数 432 浏览 6 评论 0原文

我正在编写一个程序,其中有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心是晴朗的。 2025-01-14 16:57:47

您必须调用

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

尚未被覆盖为 add()remove()removeAll() 才能转发到 contentPane 根据需要。

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.

凉墨 2025-01-14 16:57:47

假设您的目标是在之后添加其他内容
您清除了应该在之后调用验证的框架
添加这些组件来更新它

getContentPane().removeAll();
add(/*a new component*/);
validate();

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();
原野 2025-01-14 16:57:47
getContentPane().removeAll();
getContentPane().repaint();
getContentPane().removeAll();
getContentPane().repaint();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文