代码之家  ›  专栏  ›  技术社区  ›  VICWICIV

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

  •  0
  • VICWICIV  · 技术社区  · 8 年前

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

    for (Component myComps : compPanel.getComponents()){
    
                    myComps.setEnabled(false);
    
        }
    

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

    JFrame--->主要JPanel--->目标JPanel(代码中的compPanel)---->目标组件

    提前谢谢!感谢您的帮助!

    1 回复  |  直到 8 年前
        1
  •  1
  •   Sergiy Medvynskyy    8 年前

    我已经写了一个方法,可以用来获取所有组件,即使它们被放置在嵌套面板中。例如,该方法可以让您 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);
    
    }