How to get all elements inside a JFrame?

家住魔仙堡 提交于 2019-11-27 04:24:45

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.

Look at the doc for JFrame. Everything you put in a JFrame is actually put in a root pane contained in the frame.

for (Component c : this.getRootPane().getComponents())    
            for (Component c : mainPanel.getComponents()) {
                for (Component sc : ((JPanel) c).getComponents()) {
                    if (sc instanceof JTextField) {
                        //process
                    }
                }
            }

in my code, im just getting all instances of jtextfield. u can use same logic. this is just example of getting all sub-components from components you have taken. Hope it will help u out.

If you want to find all components of a given type, then you can use this recursive method!

public static <T extends JComponent> List<T> findComponents(
    final Container container,
    final Class<T> componentType
) {
    return Stream.concat(
        Arrays.stream(container.getComponents())
            .filter(componentType::isInstance)
            .map(componentType::cast),
        Arrays.stream(container.getComponents())
            .filter(Container.class::isInstance)
            .map(Container.class::cast)
            .flatMap(c -> findComponents(c, componentType).stream())
    ).collect(Collectors.toList());
}

and it can be used like this:

// list all components:
findComponents(container, JComponent.class).stream().forEach(System.out::println);
// list components that are buttons
findComponents(container, JButton.class).stream().forEach(System.out::println);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!