简体   繁体   English

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

[英]Reason for calling setEnabled(false) in JPanel

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 . 我现在正在研究Swing一段时间,但是当我不得不在JPanel调用setEnabled(false)时,我从未遇到过这种情况。 Still, I see such code sometimes in some sophisticated gui. 不过,我有时会在一些复杂的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 . 所以,当你需要在JPanel上使用setEnabled(false)时,请给我一些现实常见情况的例子。

Also in javadoc it says: 同样在javadoc中它说:

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. 实际上我有一个错误,因为禁用JPanel表在调整列大小时没有显示鼠标调整大小的光标。 I suspect there are other unpleasant surprises here. 我怀疑这里还有其他令人不快的意外。

One reason is so that getEnabled() will reflect the correct state. 一个原因是getEnabled()将反映正确的状态。 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()来测试面板的状态,以确定应用程序中不同点的操作。

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来问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM