First of all, let me say that I dont use the DefaultTreeModel. I implement my own TreeModel, so i cant use the DefaultXXX stuff. The problem is this: Through some addStuff()
Yesterday I struggeled around to fix the same issue. The requirement was to insert and remove nodes on the fly, without collapsing the the expanded tree nodes. I browsed the web and found a bunch of possible solutions, until I stumbled over this thread. Then I applied the anwser from 'Dmitry Frank' with the TreeModelEvent
. I was a bit confused, why it is such a big issue to just insert or remove a simple node and let the rest of the JTree
untouched!
Finally the plain vanilla examples from java2s helped me to find the probably simplest solution at all. (Neither a call like: nodeStructureChanged
, nodeChanged
, nodesWereRemoved
, nodesWereInserted
, etc. nor a TreeModelEvent
like suggested by 'Dmitry Frank' was required.)
Here's my solution:
// Remove a node
treeModel.removeNodeFromParent(myNode);
// Insert a node (Actually this is a reinsert, since I used a Map called `droppedNodes` to keep the previously removed nodes. So I don't need to reload the data items of those nodes.)
MyNode root = treeModel.getRootNode();
treeModel.insertNodeInto(droppedNodes.get(nodeName), root, root.getChildCount());
Keep it simple ;)