Reason for calling setEnabled(false) in JPanel

末鹿安然 提交于 2019-12-08 18:06:30

问题


I am working on Swing for a while now but never had a situation in practice when I had to call setEnabled(false) in JPanel. Still, I see such code sometimes in some sophisticated gui. But I really don't undarstand why someone wants to use it? So, please give me some examples of real life common situations when you need to use setEnabled(false) on JPanel.

Also in javadoc it says:

Disabling a component does not disable its children.

actually I had a bug because table inside disabled JPanel didn't show mouse resize cursor when resizing columns. I suspect there are other unpleasant surprises here.


回答1:


One reason is so that getEnabled() will reflect the correct state. Consider a case where some event handler wants to flag the panel as no longer enabled and it is not prudent at the time of the event to iterate over and disable all child components. Other parts of the app might need to test the state of the panel via getEnabled() to determine what to do at different points in the app.

I personally never had to do this but now that you asked and got me thinking I might use this sometime. Thanks. &&+=1 to the question.




回答2:


Starter code to enable/disable all components in a container.

JPanel p = new JPanel();
p.setEnabled(state);
setEnabledAll(p, state);

public void setEnabledAll(Object object, boolean state) {
    if (object instanceof Container) {
        Container c = (Container)object;
        Component[] components = c.getComponents();
        for (Component component : components) {
            setEnabledAll(component, state);
            component.setEnabled(state);
        }
    }
    else {
        if (object instanceof Component) {
            Component component = (Component)object;
            component.setEnabled(state);
        }
    }
}


来源:https://stackoverflow.com/questions/9730520/reason-for-calling-setenabledfalse-in-jpanel

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