Select 只有在 Swing 中选择所有子节点时才为父节点

Select parent node only if all children are selected in Swing

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

Java Swing: Need a good quality developed JTree with checkboxes

但是当我单击单个子节点时,父节点也得到 selected。但我只想 select 父节点只有当它的所有子节点都被 select 编辑时,否则未被 select 编辑。

只需添加此代码

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