Search code examples
javaswingnestedjpaneljcomponent

How to disable the child-components of a nested JPanel but keep the panel itself usable


So, in my JPanel I have several components. Becuase I want the user to be able to add components to the JPanel using the mouse, I want to disable all the child-components already present in the panel so the user can't click them when adding new components. I want to know how to disable all the components that are inside my original JPanel. I have tried using the following:

for (Component myComps : compPanel.getComponents()){

                myComps.setEnabled(false);

    }

The components are located in a nested JPanel, the order would be

JFrame ---> Main JPanel ---> Target JPanel (compPanel in the code) ---> Target Components

Thanks in advance! All help is appreciated!


Solution

  • I've written a method which can be used to get all components even if they laid out in nested panels. The method can for example get you all JButton objects in your panel. But if you want to disable all components you should search for JComponent.class.

    /**
     * Searches for all children of the given component which are instances of the given class.
     *
     * @param aRoot start object for search.
     * @param aClass class to search.
     * @param <E> class of component.
     * @return list of all children of the given component which are instances of the given class. Never null.
     */
    public static <E> List<E> getAllChildrenOfClass(Container aRoot, Class<E> aClass) {
        final List<E> result = new ArrayList<>();
        final Component[] children = aRoot.getComponents();
        for (final Component c : children) {
            if (aClass.isInstance(c)) {
                result.add(aClass.cast(c));
            }
            if (c instanceof Container) {
                result.addAll(getAllChildrenOfClass((Container) c, aClass));
            }
        }
        return result;
    }
    

    So in your case you must rewirite your loop as following:

    for (Component myComps : getAllChildrenOfClass(compPanel, JComponent.class)){
    
                myComps.setEnabled(false);
    
    }