How can I refresh a JTree after adding some nodes to the underlying model?

前端 未结 8 2078
情歌与酒
情歌与酒 2020-12-08 21:42

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()

8条回答
  •  有刺的猬
    2020-12-08 22:09

    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 ;)

提交回复
热议问题