How to update JTree elements

☆樱花仙子☆ 提交于 2019-11-28 10:50:25

问题


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


回答1:


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.




回答2:


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.




回答3:


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

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




回答4:


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.




回答5:


Are you using DefaultTreeModel?

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



来源:https://stackoverflow.com/questions/2730851/how-to-update-jtree-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!