在 Java Swing 中循环遍历容器内的嵌套容器
Loop through nested containers inside a container in Java Swing
因此,我正在开发此应用程序,其中 JPanel
对象填充了外部面板。我想遍历外部面板内部的面板(因为它们是动态插入的,我不知道会有多少)并访问它们的组件。但是,似乎只有 .getComponentCount()
和 getComponent()
为面板定义,它不允许我查找它的嵌套组件。
for(int i = 0; i < pl.playlistDisplay.getComponentCount(); i++)
{
// for(int j = 0; j < pl.playlistDisplay.getComponent(i).getComponentCount()) //line with the problem
pl.playlistDisplay.getComponent(i).setForeground(baseColor);
}
有没有像 .getContainerCount() 这样的东西可以代替我使用?或任何其他方式能够访问嵌套容器的组件?
是的,容器 class 有一个 getComponentCount()
方法,您可以调用 instanceof
来查看您的 Component
是否是 Container
,投它到 Container
,调用此方法,然后以这种方式递归地遍历 container/component 树,直到找到感兴趣的 JPanel
– 但是为什么要在更好的情况下让自己经历风险和麻烦有解决方案吗?
只需保留感兴趣的组件的引用并以这种方式访问它们。即使在 运行 时间内添加了组件,也没有理由不能够设置您的代码以在需要时轻松安全地存储对它的引用。这将是一个比您正在尝试遍历组件树更强大的解决方案。
因此,我正在开发此应用程序,其中 JPanel
对象填充了外部面板。我想遍历外部面板内部的面板(因为它们是动态插入的,我不知道会有多少)并访问它们的组件。但是,似乎只有 .getComponentCount()
和 getComponent()
为面板定义,它不允许我查找它的嵌套组件。
for(int i = 0; i < pl.playlistDisplay.getComponentCount(); i++)
{
// for(int j = 0; j < pl.playlistDisplay.getComponent(i).getComponentCount()) //line with the problem
pl.playlistDisplay.getComponent(i).setForeground(baseColor);
}
有没有像 .getContainerCount() 这样的东西可以代替我使用?或任何其他方式能够访问嵌套容器的组件?
是的,容器 class 有一个 getComponentCount()
方法,您可以调用 instanceof
来查看您的 Component
是否是 Container
,投它到 Container
,调用此方法,然后以这种方式递归地遍历 container/component 树,直到找到感兴趣的 JPanel
– 但是为什么要在更好的情况下让自己经历风险和麻烦有解决方案吗?
只需保留感兴趣的组件的引用并以这种方式访问它们。即使在 运行 时间内添加了组件,也没有理由不能够设置您的代码以在需要时轻松安全地存储对它的引用。这将是一个比您正在尝试遍历组件树更强大的解决方案。