如何禁用嵌套 JPanel 的子组件但保持面板本身可用

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

所以,在我的 JPanel 中,我有几个组件。因为我希望用户能够使用鼠标将组件添加到 JPanel,所以我想禁用面板中已经存在的所有子组件,以便用户在添加新组件时无法单击它们。我想知道如何禁用我原来的 JPanel 中的所有组件。我尝试使用以下内容:

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

                myComps.setEnabled(false);

    }

组件位于嵌套的 JPanel 中,顺序为

JFrame ---> Main JPanel ---> Target JPanel(代码中的compPanel)---> Target Components

提前致谢!感谢所有帮助!

我编写了一种方法,可用于获取所有组件,即使它们位于嵌套面板中。例如,该方法可以为您获取面板中的所有 JButton 个对象。但是如果你想禁用所有组件,你应该搜索 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;
}

因此,在您的情况下,您必须按如下方式重新编写循环:

for (Component myComps : getAllChildrenOfClass(compPanel, JComponent.class)){

            myComps.setEnabled(false);

}