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

时间:2018-05-17 13:50:17

标签: java swing nested jpanel jcomponent

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

fatal error

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

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

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

1 个答案:

答案 0 :(得分:1)

我编写了一个方法,即使它们在嵌套面板中布局,也可用于获取所有组件。例如,该方法可以获取面板中的所有CREATE TABLE Orders ( CustomerID VARCHAR(10) NOT NULL, OrderDate DATE NOT NULL, ShipDate DATE NOT NULL, TotalOrderAmount DECIMAL(10,2) NOT NULL, PRIMARY KEY (CustomerID, ShipDate), FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) ) 个对象。但是,如果要禁用所有组件,则应搜索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;
}