Java Swing - How to disable a JPanel?

时间秒杀一切 提交于 2021-02-07 11:17:45

问题


I have several JComponents on a JPanel and I want to disable all of those components when I press a Start button.

At present, I am disabling all of the components explicitly by

component1.setEnabled(false);
:
:

But Is there anyway by which I can disable all of the components at once? I tried to disable the JPanel to which these components are added by

panel.setEnabled(false);

but it didn't work.


回答1:


The panel should have a getComponents() method which can use in a loop to disable the sub-components without explicitly naming them.




回答2:


The Disabled Panel provides support for two approaches. One to recursively disable components, the other to "paint" the panel with a disabled look.




回答3:


Use the JXLayer, with LockableUI.




回答4:


The following method uses recursion to achieve this. Pass in any Container, and this method will return a Component array of all of the non-Container components located anywhere "inside" of the Container.

    private Component[] getComponents(Component container) {
        ArrayList<Component> list = null;

        try {
            list = new ArrayList<Component>(Arrays.asList(
                  ((Container) container).getComponents()));
            for (int index = 0; index < list.size(); index++) {
                for (Component currentComponent : getComponents(list.get(index))) {
                    list.add(currentComponent);
                }
            }
        } catch (ClassCastException e) {
            list = new ArrayList<Component>();
        }

        return list.toArray(new Component[list.size()]);
        }
    }

Simply loop through the elements of the returned array and disable the components.

for(Component component : getComponents(container)) {
    component.setEnabled(false);
}



回答5:


The following method should be all what you need to add, you can call it with setEnableRec(panel, true) or setEnableRec(panel, false):

private void setEnableRec(Component container, boolean enable){
    container.setEnabled(enable);

    try {
        Component[] components= ((Container) container).getComponents();
        for (int i = 0; i < components.length; i++) {
            setEnableRec(components[i], enable);
        }
    } catch (ClassCastException e) {

    }
}



回答6:


Disabling should occur recursively:

Queue<Component> queue = new LinkedList<>(Arrays.asList(container.getComponents()));
while(!queue.isEmpty()) {
    Component head = queue.poll();
    head.setEnabled(enable);
    if(head instanceof Container) {
        Container headCast = (Container) head;
        queue.addAll(Arrays.asList(headCast.getComponents()));
    }
}


来源:https://stackoverflow.com/questions/2713425/java-swing-how-to-disable-a-jpanel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!