【问题标题】:Select parent node only if all children are selected in Swing仅当在 Swing 中选择了所有子节点时才选择父节点
【发布时间】:2015-10-10 12:29:48
【问题描述】:

我正在开发一个 IntelliJ 插件,它将弹出对话框以检查来自 CheckboxTree 的值。为此,我正在关注以下问答:

Java Swing: Need a good quality developed JTree with checkboxes

但是当我单击单个子节点时,父节点也会被选中。但是我只想在所有子节点都被选中时才选择父节点,否则未选中。

【问题讨论】:

  • 如果没有选择所有子节点,您可以添加到 addCheckChangeEventListener -> 一个“取消选中父节点”

标签: java swing checkbox jtree


【解决方案1】:

只需添加此代码

updatePredecessorsWithCheckMode函数中注释如下代码,并在for循环后添加代码

// If at least one child is selected, selecting also the parent
//            if (childCheckedNode.isSelected) {
//                parentCheckedNode.isSelected = true;
//            }
        }
   //check the parent if all children are selected
    if (parentCheckedNode.allChildrenSelected) {
        parentCheckedNode.isSelected = true;
    }

完整功能供参考

// When a node is checked/unchecked, updating the states of the predecessors
protected void updatePredecessorsWithCheckMode(TreePath tp, boolean check) {
    TreePath parentPath = tp.getParentPath();
    // If it is the root, stop the recursive calls and return
    if (parentPath == null) {
        return;
    }
    CheckedNode parentCheckedNode = nodesCheckingState.get(parentPath);
    DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) parentPath.getLastPathComponent();
    parentCheckedNode.allChildrenSelected = true;
    parentCheckedNode.isSelected = false;
    for (int i = 0; i < parentNode.getChildCount(); i++) {
        TreePath childPath = parentPath.pathByAddingChild(parentNode.getChildAt(i));
        CheckedNode childCheckedNode = nodesCheckingState.get(childPath);
        // It is enough that even one subtree is not fully selected
        // to determine that the parent is not fully selected
        if (!childCheckedNode.allChildrenSelected) {
            parentCheckedNode.allChildrenSelected = false;
        }
        // If at least one child is selected, selecting also the parent
       // if (childCheckedNode.isSelected) {
        //    parentCheckedNode.isSelected = true;
       // }
    }
   //check the parent if all children are selected
    if (parentCheckedNode.allChildrenSelected) {
        parentCheckedNode.isSelected = true;
    }
    if (parentCheckedNode.isSelected) {
        checkedPaths.add(parentPath);
    } else {
        checkedPaths.remove(parentPath);
    }
    // Go to upper predecessor
    updatePredecessorsWithCheckMode(parentPath, check);
}

【讨论】:

  • @Madhan:非常感谢您的帮助......它工作得非常好...... :)
  • @Mashan 需要更多帮助。复选框的字符串长度很大。但它只显示2个字符。我正在使用以下代码更改布局 chechBoxTree.setLayout(new BoxLayout(chechBoxTree, BoxLayout.PAGE_AXIS)); chechBoxTree.setSize(800,300);但它没有反映在 UI 中。请帮忙。
  • @user667505 我听不懂。如果文本太大,是否只显示两个字符,后跟两个点或类似的东西。如果是这样,请尝试((DefaultTreeModel)tree.getModel()).reload();。否则,请进一步解释问题或将其作为不同的问题发布
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多