如何获取JFrame中的所有元素? [英] How to get all elements inside a JFrame?

查看:456
本文介绍了如何获取JFrame中的所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码来获取我需要的所有元素并进行一些处理。问题是我需要指定每个面板来获取其中的元素。

I have this code to get all the elements I need and do some processing. The problem is I need to specify every panel I have to get the elements inside it.

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

我想做这样的事情并得到所有元素无需拼写所有面板名称。我是怎么做到的下面的代码没有获得所有元素。

I want to do something like this and get all the elements without need specefy all the panels names. How I do this. The code below don't get all the elements.

for (Component c : this.getComponents()) {
    //processing
}


推荐答案

你可以写一个递归方法并递归每个容器:

You can write a recursive method and recurse on every container:

此网站提供了一些示例代码:

This site provides some sample code:

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;
}

如果你只想要直接子组件的组件,你可以限制递归深度为2。

If you only want the components of the immediate sub-components, you could limit the recursion depth to 2.

这篇关于如何获取JFrame中的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆