gpt4 book ai didi

java - Jtree 仅选择子节点而不选择父节点

转载 作者:太空宇宙 更新时间:2023-11-04 06:35:56 24 4
gpt4 key购买 nike

我正在使用 Jtree,但我被困在一个地方执行以下操作,

Diagram

来自图:2 我单击 A(复选框),它的所有子项都被选中 - 没关系

来自图:3我单击了 D(CheckBox),它的所有父项(A、B、C)也都被选中。

现在我想做的是,

If i select A -> A,B,C,D will eb selected
If i Select B-> only B,C,D
If c -> C,D
If D-> Only D

我使用的代码是:

public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus){ 

//delegate is TreeCellrenderer
Component renderer = delegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
TreePath path = tree.getPathForRow(row);
if(path!=null)
{
//Selection Model is TreeSelection Model
if(selectionModel.isPathSelected(path, true)) //Below code.
{
checkBox.setState(checkBox.SELECTED);
if (selected)
{
//Comes here If check box is selected by mouse click
}
}
else
{
checkBox.setState(checkBox.NOT_SELECTED);
}
}
add(checkBox, BorderLayout.WEST);
add(renderer, BorderLayout.CENTER);
return this;
}

isPathSelected 方法:

// tells whether given path is selected. 
// if dig is true, then a path is assumed to be selected, if
// one of its ancestor is selected.
public boolean isPathSelected(TreePath path, boolean dig){
if(!dig){
return super.isPathSelected(path);
}

while(path!=null && !super.isPathSelected(path)){
path = path.getParentPath();
}

return path!=null;
}

我不确定我这样做是否是 Jtree 的新手。请帮忙

最佳答案

您必须“遍历”树元素的子节点:

public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus){
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
walkThroug(node, isSelected);
}

private void walkThrough(DefaultMutableTreeNode node, boolean isSelected) {
int cc = node.getChildCount();

//TODO select current node
//something like: node.setSelected(isSelected)

for(int i = 0; i < cc; i++){
DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) node.getChildAt(i);
walkThrough(childNode, isSelected);
}
}

这是一个递归调用,它只是一个片段,但它应该以这种方式工作...也许它需要“walkThrough”方法上的一些其他参数...

我断言您的对象(值)是一个 DefaultMutableTreeNode,如 http://docs.oracle.com/javase/tutorial/uiswing/components/tree.html 中所述。

关于java - Jtree 仅选择子节点而不选择父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25397655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com