我遇到了一个问题,该问题也被描述过 here .
我在 MyTree
类中有 invertExpand
方法,其工作原理如下:
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);
}
}
但问题是 isExpanded()
方法使用 HashMap
来存储展开的路径。对于新创建的TreePath
,isExpanded()
似乎永远不会返回true
。 (但它们确实扩展了)
有什么办法可以解决这个问题吗?
最佳答案
展开/折叠适用于非叶节点,因此请确保相关节点不是叶节点:
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);
}
}
编辑(根据OP的评论)
错误行为的真正原因是自定义节点中错误地实现了 hasCode,这混淆了 Map(存储扩展路径的位置)。
关于java - JTree:TreeNode 和 TreePath 之间缺少链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17703470/