Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

java - How to get all elements inside a 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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...