How to get all elements inside a JFrame?

后端 未结 4 1407
悲哀的现实
悲哀的现实 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  List findComponents(
        final Container container,
        final Class 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);
    

提交回复
热议问题