【问题标题】:How to set the checkbox setSelected() of child components using getComponent() [duplicate]如何使用 getComponent() 设置子组件的复选框 setSelected() [重复]
【发布时间】:2016-03-23 14:11:44
【问题描述】:

我正在尝试将所有复选框的值设置为setSelected(false)。这些复选框来自具有其他子面板的不同子面板。 getComponents(panelName) 只获取其中包含的组件,而不是子面板的每个子面板/子面板......等等。

在上面,allPermissionsJPanel 是父面板。 settingsButtonPanelcardContainerPanel 作为第一级子面板,我希望将每个 JCheckBox 设置为 false。

我该怎么做?我尝试使用getComponents(),但它没有从子面板的子面板中返回所有复选框。

这是我的代码。

List<Component> allPermissionsCheckboxes =fm.getComponentsAsList(allPermissionsJPanel);


        for(Component c: allPermissionsCheckboxes){
            if(c instanceof JCheckBox){
                ((JCheckBox) c).setSelected(false);
            }
        }

我尝试检查与getComponents() 相关的其他方法,但我没有找到一种方法可以遍历子面板的每个子面板,因此我可以检查它是否是instanceofJCheckBox。有什么建议吗?

【问题讨论】:

  • @CubeJockey,谢谢。你的得到批准,寿。奇怪。
  • @BPS,是的,一旦您达到 2k rep 限制,您的编辑就不会进入建议队列并自动获得批准。

标签: java swing list jcheckbox


【解决方案1】:

您需要将此实现为一种递归方法,该方法遍历组件层次结构以查找复选框并执行setSelected(false)

该方法可能如下所示:

public void deselectAllCheckBoxes(Component panel) {
    List<Component> allComponents = fm.getComponentsAsList(panel);

    for (Component c : allComponents) { // Loop through all the components in this panel
        if (c instanceof JCheckBox) { // if a component is a check box, uncheck it.
            ((JCheckBox) c).setSelected(false);
        } else if (c instanceof JPanel) { // if a component is a panel, call this method
            deselectAllCheckBoxes(c);     // recursively.
    }
}

那么你只需拨打deselectAllCheckBoxes(allPermissionsPanel);

【讨论】:

  • 根据您的建议递归解决了我的问题。谢谢。这很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 2017-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多