在 Java GUI 中更新 JTree

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3821782/
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-30 03:32:01  来源:igfitidea点击:

updating JTree in java GUI

javajtree

提问by sajad

I used a JTree in my GUI and added it to a JFrame. When I want to update it and change it's nodes in another part of my program (while program is running, as an action performed) I try to add new nodes, or remove nodes to it; But my interface doesn't change. Please suggest me a solution.

我在 GUI 中使用了 JTree 并将其添加到 JFrame。当我想更新它并在我的程序的另一部分更改它的节点时(在程序运行时,作为执行的操作),我尝试添加新节点或删除节点;但是我的界面没有改变。请建议我一个解决方案。

regards

问候

回答by camickr

In addition to the insertNodeInto suggestion you can also use:

除了 insertNodeInto 建议,您还可以使用:

DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode)model.getRoot();
root.add(new DefaultMutableTreeNode("another_child"));
model.reload(root);

回答by Adamski

You need to ensure that after updating your model you instruct it to fire an event to cause any registered listeners to be notified of the event. One of the listeners will be the JTreeand upon receiving the event it will repaint.

您需要确保在更新您的模型后,您指示它触发一个事件,以使任何注册的侦听器都收到该事件的通知。其中一个侦听器将是JTree并且在接收到事件后它将重新绘制。

For example, DefaultTreeModelcontains the methods:

例如,DefaultTreeModel包含方法:

nodeChangednodesChangednodeStructureChangednodesWereInsertednodesWereRemoved

nodeChangednodesChangednodeStructureChangednodesWereInsertednodesWereRemoved

Also, as with all Swing programming you need to ensure you are updating your model on the Event Dispatch Thread.

此外,与所有 Swing 编程一样,您需要确保在Event Dispatch Thread上更新模型。

回答by Bryan

Do you mean the GUI aspect just isn't showing your change? You should probably look int repaint()and revalidate().

您的意思是 GUI 方面没有显示您的更改吗?你可能应该看看 intrepaint()revalidate().

Here'sa good description of when to call which one.

这里有一个关于何时调用哪个的很好的描述。