Java 在 JPanel 中调用 setEnabled(false) 的原因

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9730520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:50:17  来源:igfitidea点击:

Reason for calling setEnabled(false) in JPanel

javaswingjpanel

提问by GrayR

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.

我现在在 Swing 上工作了一段时间,但在实践中从来没有遇到过我不得不打电话的setEnabled(false)情况JPanel。尽管如此,我有时会在一些复杂的 gui 中看到这样的代码。但我真的不明白为什么有人要使用它?所以,当你需要使用setEnabled(false)on时,请给我一些现实生活中常见情况的例子JPanel

Also in javadoc it says:

同样在javadoc中它说:

Disabling a component does not disable its children.

禁用组件不会禁用其子组件。

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

实际上我有一个错误,因为JPanel在调整列大小时禁用的表没有显示鼠标调整大小光标。我怀疑这里还有其他不愉快的惊喜。

采纳答案by Java42

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.

原因之一是 getEnabled() 将反映正确的状态。考虑这样一种情况,某些事件处理程序想要将面板标记为不再启用​​,并且在事件发生时迭代并禁用所有子组件是不谨慎的。应用程序的其他部分可能需要通过 getEnabled() 测试面板的状态,以确定在应用程序中的不同点要执行的操作。

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.

我个人从来没有这样做过,但现在你问了,让我觉得我可能会在某个时候使用它。谢谢。&&+=1 的问题。

回答by Java42

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);
        }
    }
}