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

查看:42
本文介绍了如何获取 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:

本站提供了一些示例代码:

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天全站免登陆