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

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

本文介绍了如何从Java中的JFrame中删除所有组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,我有一个JFrame,我想从中删除所有组件,然后只添加一个组件并重新绘制框架。到目前为止我所拥有的是类似下面的代码(在实现JFrame的对象中调用,其中StartPanel实现JPanel):

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();

然而,当我运行代码时,它会显示一个空窗口(不是startPanel),当我最小化时/调整窗口大小,窗口变黑。如果我省略 removeAll()并且JFrame上已经没有元素,那么它就会显示startPanel。有关如何实际删除所有内容,然后让新面板仍然显示的任何想法?

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?

推荐答案

你必须致电

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

removeAll()尚未被覆盖为 add() remove()转发到 contentPane 必要时。

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

这篇关于如何从Java中的JFrame中删除所有组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 08:36