JTree: TreeNode和TreePath之间缺少的链接。

时间:2022-04-02 12:32:33

I have a problem which was also described here.

这里也有一个问题。

I have the invertExpand method in MyTree class which works like this:

我在MyTree类中有一个反扩展的方法,它的工作原理是这样的:

public void invertExpand(DefaultMutableTreeNode node) {
    TreePath path = new TreePath(node.getPath()); // no better way to get TreePath from TreeNode :(
    if (!isExpanded(path)) {
        expandPath(path);
    } else {
        collapsePath(path);
    }
}

But the problem is isExpanded() method uses the HashMap to store the expanded paths. It seems that isExpanded() never returns true for newly created TreePath. (But they are expanded really)

但问题是isExpanded()方法使用HashMap来存储扩展路径。看起来isExpanded()从来不会返回新创建的TreePath。(但它们确实扩大了)

Does any way to fix that issue?

有没有办法解决这个问题?

1 个解决方案

#1


4  

Expand/collapse works on non-leaf nodes, so be sure that the node in question is not a leaf:

展开/折叠在非叶节点上的工作,所以请确保所讨论的节点不是叶子:

public void invertExpand(DefaultMutableTreeNode node) {
    if (node.isLeaf()) 
        node = (DefaultMutableTreeNode) node.getParent();
    TreePath path = new TreePath(node.getPath()); // no better way to get TreePath from TreeNode :(
    if (isExpanded(path)) {
        collapsePath(path);
    } else {
        expandPath(path);
    }
}

Edit (as per OP's comment)

编辑(按OP的评论)

The real reason for the misbehaviour was an incorrectly implemented hasCode in a custom node which confused the Map (where the expanded paths are stored).

错误行为的真正原因是在一个自定义节点中错误地实现了hasCode,它混淆了映射(扩展路径存储在哪里)。

#1


4  

Expand/collapse works on non-leaf nodes, so be sure that the node in question is not a leaf:

展开/折叠在非叶节点上的工作,所以请确保所讨论的节点不是叶子:

public void invertExpand(DefaultMutableTreeNode node) {
    if (node.isLeaf()) 
        node = (DefaultMutableTreeNode) node.getParent();
    TreePath path = new TreePath(node.getPath()); // no better way to get TreePath from TreeNode :(
    if (isExpanded(path)) {
        collapsePath(path);
    } else {
        expandPath(path);
    }
}

Edit (as per OP's comment)

编辑(按OP的评论)

The real reason for the misbehaviour was an incorrectly implemented hasCode in a custom node which confused the Map (where the expanded paths are stored).

错误行为的真正原因是在一个自定义节点中错误地实现了hasCode,它混淆了映射(扩展路径存储在哪里)。