Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updating JTree in java GUI

Tags:

java

jtree

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.

regards

like image 589
sajad Avatar asked Sep 29 '10 12:09

sajad


2 Answers

In addition to the insertNodeInto suggestion you can also use:

DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode)model.getRoot();
root.add(new DefaultMutableTreeNode("another_child"));
model.reload(root);
like image 147
camickr Avatar answered Oct 02 '22 22:10

camickr


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 JTree and upon receiving the event it will repaint.

For example, DefaultTreeModel contains the methods:

nodeChanged nodesChanged nodeStructureChanged nodesWereInserted nodesWereRemoved

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

like image 28
Adamski Avatar answered Oct 02 '22 22:10

Adamski