[英]How can I setVisible for all JPanel's on JFrame
How can I setVisible for all JPanel on JFrame? 如何在JFrame上为所有JPanel设置setVisible? I know that I can use JFrame.JPanel.setVisible for each panel, but I'd like do it ones for all.
我知道我可以为每个面板使用JFrame.JPanel.setVisible,但我想为所有人做这些。
It's very usefull because I don't know witch panel are visible. 它非常有用,因为我不知道巫婆面板是可见的。 So I want hide all panel after action and show 1 or 2 panels.
所以我想在行动后隐藏所有面板并显示1或2个面板。
Simple solution : 简单方案 :
store all your panels as instances or in a list 将所有面板存储为实例或列表
Generic solution : 通用解决方案 :
iterate the widget tree 迭代小部件树
private void setAllChildPanelsVisible(Container parent) {
Component[] components = parent.getComponents();
if (components.length > 0) {
for (Component component : components) {
if (component instanceof JPanel) {
((JPanel) component).setVisible(true);
}
if (component instanceof Container) {
setAllChildPanelsVisible((Container) component);
}
}
}
}
How to use it: 如何使用它:
@Test
public void testSetAllChildPanelsVisible() {
JFrame frame = new JFrame();
JPanel panel1 = new JPanel();
frame.getContentPane().add(panel1);
JPanel panel2 = new JPanel();
panel1.add(panel2);
panel1.setVisible(false);
panel2.setVisible(false);
assertFalse(panel1.isVisible());
assertFalse(panel2.isVisible());
setAllChildPanelsVisible(frame.getContentPane());
assertTrue(panel1.isVisible());
assertTrue(panel2.isVisible());
}
Here's a generic method which does this. 这是一个执行此操作的通用方法。 It recurively iterates through all the components in a container hierarchy, finds the ones that match a particular component class, and sets their visible property:
它反复遍历容器层次结构中的所有组件,找到与特定组件类匹配的组件,并设置其可见属性:
static void setComponentVisibility(Container container,
Class<? extends Component> componentClass, boolean visible) {
for (Component c : container.getComponents()) {
if (componentClass.isAssignableFrom(c.getClass())) {
c.setVisible(visible);
} else if (c instanceof Container) {
setComponentVisibility((Container)c, componentClass, visible);
}
}
}
Use it something like this: 使用这样的东西:
setComponentVisibility(frame, JPanel.class, false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.