I have a List of "Books" to render in a tree format. Each book have 3 Set, one of "Character", one of "Chapter", and one of "Picture".
I want to display a tree like that
Books |- Book 1 | |-Chapters | | |- Chapter 1 | | |- Chapter 2 | |-Characters | | |- Character 1 |- Book 2 |-Chapters
Empty Sets MUST be displayed for popup menu's sakes.
Books |- New Book | |-Chapters | |-Characters
Since I didn't want to synchronize a tree of DefaultMutableTreeNode with my Book List, I created a custom TreeModel (BookTreeModel).
My method getChild(Node parent, int index) return either the initial Books List (for the root node), either a "Book" object, either a Set for the node "Characters", "Chapters", "Pictures", and "Character" "Picture" an "Chapter" when exploring the Sets.
My problem is that it appears that the two empty sets are supposed to be "equals" for the java language.
So When I return several empty sets (a newly created Book doesn't contains any chapters not pictures yet, so the sets are empty ! ), the tree considers them as the SAME NODE, so my Tree contains holes in it ! Only the last returned empty Set is displayed (logic).
Since I didn't found any 'elegant' way to dodge that probleme (doesn't want to subclass Set to override equals or such a ugly thing), I'm returning to the community to point me towards an elegant one !
Here's a suggestion that uses off–the–shelf classes to put this together. In the JTree in the app below each TreeNode is a DefaultMutableTreeNode. The getUserObject method of the DefaultMutableTreeNode calls the toString method of the object given to the DefaultMutableTreeNode as userObject. To allow the Book class to avoid its toString method being called by getUserObject, the Book is wrapped in a BookWrapper whose toString method returns the Book title to the inquiring getUserObject method. This leaves the Book class toString method free to return its relevant data.