【问题标题】:JTree: Missing link between TreeNode and TreePathJTree:TreeNode 和 TreePath 之间缺少链接
【发布时间】:2013-07-17 15:06:30
【问题描述】:

我有一个问题,也被描述为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 来存储扩展路径。似乎isExpanded() 永远不会为新创建的TreePath 返回true。 (但它们确实被扩展了)

有什么办法可以解决这个问题吗?

【问题讨论】:

  • 好吧,下次展示一个演示问题的 SSCCE(而不是将任务留给回答者;-)

标签: java swing jtree treenode


【解决方案1】:

展开/折叠适用于非叶节点,因此请确保所讨论的节点不是叶:

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(存储扩展路径的位置)。

【讨论】:

  • 好吧,那么您的节点实现不正确 - 叶子无法展开,因此请获取您所要求的(从树中 ;-) BTW:现在是真的时间了对于一个sscce,没有办法回答你的问题......
  • hmm @kleopatra 请回复isExpanded()expandPath()collapsePath() 使用HashMap 所以我需要检查equals()hashCode() 的覆盖。
  • 嗯,好奇:为什么你覆盖了equals,这有点不寻常?
  • 我的节点相当复杂,不应该用所有字段来确定它的相等性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-27
  • 1970-01-01
  • 2019-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多