How to get all elements inside a JFrame?

后端 未结 4 1387
悲哀的现实
悲哀的现实 2020-11-28 10:52

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.

fo         


        
相关标签:
4条回答
  • 2020-11-28 11:14

    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);
    
    0 讨论(0)
  • 2020-11-28 11:23

    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.

    0 讨论(0)
  • 2020-11-28 11:25

    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())    
    
    0 讨论(0)
  • 2020-11-28 11:25
                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.

    0 讨论(0)
提交回复
热议问题