java 如何更新 JTree 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2730851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:34:40  来源:igfitidea点击:

How to update JTree elements

javaswingjtree

提问by ibrahimyilmaz

I use JTree with TreeNode which extending DefaultMutableTreeNode.when I add new node,i cant update JTree.Any help will be appreciated

我将 JTree 与 TreeNode 一起使用,它扩展了 DefaultMutableTreeNode。当我添加新节点时,我无法更新 JTree。任何帮助将不胜感激

回答by Serge Merzliakov

if you use DefaultTreeModel try to call its reload()method.

如果您使用 DefaultTreeModel 尝试调用它的reload()方法。

DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
model.reload();

//or... model.reload(nodeUpdatedByYou);

Never use tree.updateUI()as this is a look and feel operation (although it works).

切勿使用,tree.updateUI()因为这是外观操作(尽管它有效)。

回答by Sergey

Actually, it is enough to reload the parent node. Internally,

实际上,重新加载父节点就足够了。在内部,

public void reload()

is using

正在使用

public void reload(TreeNode node)

but with root as its parameter, so, unless you are updating the direct root's leaf, you are better of using a more fine-grained version.

但是以 root 作为其参数,因此,除非您要更新直接根的叶子,否则最好使用更细粒度的版本。

回答by Gnoupi

Adding to the node only is not enough, the Tree needs to be notified. The correct way to do this is to let the model take care of adding/removing nodes, as it will notify correctly the Tree on the way.

仅添加到节点是不够的,需要通知树。正确的做法是让模型负责添加/删除节点,因为它会在途中正确通知树。

In case of a DefaultTreeModel (which should be the one used in the JTree if you haven't made your own TreeModel), you have the method insertNodeInto(MutableTreeNode newChild, MutableTreeNode parent, int index), which you can use.

如果是 DefaultTreeModel(如果您还没有制作自己的 TreeModel,应该是 JTree 中使用的那个,您可以使用insertNodeInto(MutableTreeNode newChild, MutableTreeNode parent, int index)方法。

回答by Summer_More_More_Tea

Since Java use MVC to implement JTree component, your operation that add a node just change the model. Besides, you should notify representation of the tree some modifications have taken place. Try use fireTreeNodes*** methods of your tree model to notify the JTree object this kind of modification. Refer Java API for details. Good luck.

由于Java 使用MVC 来实现JTree 组件,因此您添加节点的操作只是改变了模型。此外,您应该通知树的表示已经发生了一些修改。尝试使用您的树模型的 fireTreeNodes*** 方法来通知 JTree 对象这种修改。有关详细信息,请参阅 Java API。祝你好运。

回答by ring bearer

Are you using DefaultTreeModel?

你在用DefaultTreeModel吗?

If so, when adding use insertNodeIntoAPI so that appropriate events are generated.

如果是这样,在添加时使用insertNodeIntoAPI 以便生成适当的事件。