java - 支持具有相同子节点的 JTree 节点

标签 java swing jtree treepath

我已经实现了一个 TreeModel 来适应现有的数据模型,以将其可视化为 JTree。我遇到了具有多个相同子(叶)节点的节点的问题。例如,考虑一个叶子节点为字符串的 JTree。每当父节点包含具有相同字符串值的子节点时,就会出现问题。这些叶节点的 TreePath 是相同的,并且作为字符串,equals() 返回 true。文档明确指出了这一点:

JTree and its related classes make extensive use of TreePaths for indentifying nodes in the TreeModel. If a TreeModel returns the same object, as compared by equals, at two different indices under the same parent than the resulting TreePath objects will be considered equal as well. Some implementations may assume that if two TreePaths are equal, they identify the same node. If this condition is not met, painting problems and other oddities may result. In other words, if getChild for a given parent returns the same Object (as determined by equals) problems may result, and it is recommended you avoid doing this.

有办法解决这个问题吗?到目前为止我唯一想到的(理论上 - 我还没有实现并验证它是否有效)是将 String 包装在另一个类中,重写 toString() 以返回包装的字符串,并利用默认 equals() 方法测试实际包装对象必须相同(相同实例)才能返回 true。这似乎是一个可怕的黑客行为。有人吗?

编辑:我最终使用了建议的方法。我需要支持同一字符串的多个实例作为我的应用程序的同一父级的子级,并且没有找到其他解决方法。它有效,但是...

最佳答案

我的建议是创建 TreeNode 的子类,并重写 equals 方法。 (在 TreeNode 中保存字符串)。我认为通过这个你可以使用java的DefaultTreeModel。

关于java - 支持具有相同子节点的 JTree 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26071393/

相关文章:

java - Java 中的多级(嵌套?)Jlist

java - 简单的 Spring Security 要求

Java 安全 - 使用公钥的 X509 证书验证

java - JComponent.setBounds 最后一个 JComponent 在错误的位置

java - 键盘 Action 监听器

java - 从 JComboBox 选择项目时显示 Jtree?

java - Java JTree的右键单击上下文菜单?

java - Math.pow(65,17) % 3233 的令人惊讶的结果

java - 在 Ubuntu Eclipse 工作区上未启动

java - 处理大量大型 jpg