Ren*_*ani 18 java swing jcomponent
我有这个代码来获取我需要的所有元素并进行一些处理.问题是我需要指定每个面板来获取其中的元素.
for (Component c : panCrawling.getComponents()) {
//processing
}
for (Component c : panFile.getComponents()) {
//processing
}
for (Component c : panThread.getComponents()) {
//processing
}
for (Component c : panLog.getComponents()) {
//processing
}
//continue to all panels
Run Code Online (Sandbox Code Playgroud)
我想做这样的事情,并获得所有的元素,而不需要specefy所有的面板名称.我是怎么做到的 下面的代码没有获得所有元素.
for (Component c : this.getComponents()) {
//processing
}
Run Code Online (Sandbox Code Playgroud)
aio*_*obe 40
您可以编写递归方法并对每个容器进行递归:
该站点提供了一些示例代码:
public static List<Component> getAllComponents(final Container c) {
Component[] comps = c.getComponents();
List<Component> compList = new ArrayList<Component>();
for (Component comp : comps) {
compList.add(comp);
if (comp instanceof Container)
compList.addAll(getAllComponents((Container) comp));
}
return compList;
}
Run Code Online (Sandbox Code Playgroud)
如果只需要直接子组件的组件,则可以将递归深度限制为2.
tot*_*to2 15
查看JFrame的doc .放入a中的所有JFrame内容实际上都放在框架中包含的根窗格中.
for (Component c : this.getRootPane().getComponents())
Run Code Online (Sandbox Code Playgroud)