Reputation: 729
I have implemented a TreeModel to adapt an existing data model for visualization as a JTree. I have hit a problem with nodes that have multiple identical child (leaf) nodes. For example, consider a JTree with leaf nodes which are Strings. There is a problem whenever a parent node contains children with the same String value. The TreePath to these leaf nodes is identical, and as Strings, equals() returns true. The documentation calls this out explicitly:
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.
Is there a way around this? The only thing I've come up with so far (theoretically - I haven't implemented and verified that it will work) is to wrap a String in another class, override toString() to return the wrapped string, and take advantage of the default equals() method which tests that the actual wrapper objects must be identical (same instance) to return true. This seems like a terrible hack. Anyone?
Edit: I ended up using the proposed method. I need to support multiple instances of the same String as children of the same parent for my application, and found no other workaround. It works, but...
Upvotes: 2
Views: 257
Reputation: 111
My advice is to create a subclass of TreeNode, and override the method equals. (Inside the TreeNode you save your string). And i think with this you can use the DefaultTreeModel of java.
Upvotes: 1