仅在Swing中选择所有子项时才选择父节点

时间:2015-07-21 07:11:12

标签: java swing checkbox jtree

我正在开发一个IntelliJ插件将弹出对话框来检查来自CheckboxTree的值。为此,我在Q& A:

下面

Java Swing: Need a good quality developed JTree with checkboxes

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

1 个答案:

答案 0 :(得分: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);
}