Search code examples
javaswingjtree

Choosing between a custom tree model or default tree model when insert/removing nodes and updating tree


I have a set of nodes for a command-line application and would like to put a GUI over it. I want to display the tree visually and am using a JTree. I have written my own tree model that implements the TreeModel interface and the tree is rendered as expected.

But now I want to be able to insert or remove nodes. Currently I am just redrawing the tree whenever I perform an insert or remove operation, which is a terrible solution especially if there are thousands of nodes.

The DefaultTreeModel handles all of the inserting and removing and tree updating as required. I would have to figure out how that works for my own model.

The sole reason for using a custom tree model is just so that I can work with the existing nodes objects. Is this reason "good enough" to implement a custom model or should I look for a way to use the default mutable tree node objects?


Solution

  • As noted in How to Use Trees: Creating a Data Model, "the TreeModel interface accepts any kind of object as a tree node." Your custom TreeModel can efficiently reflect your "pre-existing hierarchical data structure."

    As a concrete example, look at the FileTreeModel, cited here and here. The only thing missing is the TreeModelListener plumbing, instructions for which are found in the EventListenerList API.

    Addendum: Regarding rendering efficiency, JTree uses the flyweight pattern to render only visible nodes. Firing the appropriate TreeModelEvent in your TreeModel will allow the listing tree to react to changes in the model. DefaultTreeModel is a useful guide.