Java – why can’t my JTree be updated when a new node is added to the treemodel?

The defaulttreemodel I used fills in the override of defaultmutabletreenode, which supports optionally changing the display string of nodes in the tree As shown in the following code, in my form, I populate the tree for new nodes by creating them in a separate class and then passing them through the wrapper class of my master data type The process is to create a new overridden defaultmutabletreenode, add child nodes to it (each accesspoint is represented by a node with multiple child nodes), and then store it for later use in the UI

I added nodes this way for the first time, and it worked beautifully Any subsequent nodes with the following code are actually stored in the defaulttreemodel, but JTree is not updated with the new node

Why is JTree not filled after adding the first child?

private void populateAccessPointTreeModel(AccessPointDataWrapper wrapper) {
    //the pre-created DefaultMutableTreeNode subclass instance is
    // stored in the wrapper
    DefaultMutableTreeNode accessPointNode =
            wrapper.getAccessPointTreeNode();
    //this line updates the accessPointTree with the new node (I've looked at the
    // value in debug mode,and it does in fact add the node
    ((DefaultMutableTreeNode) accessPointTree.getRoot()).add(accessPointNode);
    //unrelated logic happens down here...
}

I can include the code I create nodes when necessary, but I don't think this is a problem

Solution

The problem is that defaultmutabletreenode does not notify defaulttreemodel that its children have been updated For this reason, you either want to call the appropriate method (nodesChanged or similar) in the table model, or (preferably) use DefaultTreeModel.. Insertnodesinto method

DefaultTreeModel model = (DefaultTreeModel)accessPointTree.getModel();
DefaultMutableTreeNode root = model.getRoot();
model.insertNodeInto(accessPointNode,root,root.getChildCount());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>