当TreeModel添加新节点时,为什么我的JTree不更新? [英] Why isn't my JTree updating when the TreeModel adds new nodes?

查看:231
本文介绍了当TreeModel添加新节点时,为什么我的JTree不更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用填充有DefaultMutableTreeNode替代的DefaultTreeModel,该替代支持支持更改树中节点的显示字符串.如下代码所示,在我的表单中,我通过在单独的类中创建新节点,然后将它们通过包装器类传递给我的主要数据类型,来用新节点填充树.此处的过程是创建一个新的覆盖的DefaultMutableTreeNode,向其添加子代(每个AccessPoint由具有多个子节点的一个节点表示),然后将其存储以供以后在UI中使用.

I am using a DefaultTreeModel populated with an override of DefaultMutableTreeNode which supports optionally changing the display string of a node in a tree. As shown in the code below, in my form I populate the tree with new nodes by creating them in a separate class and then passing them in via a wrapper class for my main data type. The procedure there is to create a new overridden DefaultMutableTreeNode, add children to it (each AccessPoint is represented by a node with several child nodes), then store it for later use in the UI.

我第一次以这种方式添加节点,效果很好.实际上,添加了以下代码的所有后续节点实际上都存储在DefaultTreeModel中,但是JTree不会被新节点更新.

The first time I add a node this way, it works beautifully. Any subsequent node added with the following code is in fact stored in the DefaultTreeModel, but the JTree is not being updated with the new nodes.

为什么添加第一个孩子后就没有填充JTree?

Why is it that the JTree doesn't get populated after the first child is added?

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 where I create the node if necessary, but I don't think it is the issue.

推荐答案

问题是DefaultMutableTreeNode不会通知DefaultTreeModel其子级已更新.为此,您要么要在表模型中调用适当的方法(nodesChanged或类似方法),要么(最好)使用DefaultTreeModel.insertNodesInto方法.

The problem is that DefaultMutableTreeNode does not inform the DefaultTreeModel that its children were updated. To do this you'll either want to call the appropriate method in the table model (nodesChanged or similar) or (preferably) use the DefaultTreeModel.insertNodesInto method.

DefaultTreeModel model = (DefaultTreeModel)accessPointTree.getModel();
DefaultMutableTreeNode root = model.getRoot();
model.insertNodeInto(accessPointNode, root, root.getChildCount());

这篇关于当TreeModel添加新节点时,为什么我的JTree不更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆