Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Jtree won't refresh child nodes?  RSS feed

 
Rebecca Witmer
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a jtree that needs to be refreshed by some code in another panel. IT was created like this:
top = new DefaultMutableTreeNode("Top Node Name!");
tree = new JTree(top);

So top is the top node. When I put new data in the tree the name changes from, "Top Node Name!" to the correct string. So I know _something_ is happenning. When I open up the tree initially everything looks lovely. But when I change the data in the tree, then open it up again it still shows the same children. So I created a test like this:

At the top of the createNodes method each time it runs it does this:
tree.removeAll();
top.removeAllChildren();
System.out.println("Inside create nodes method " + top.getChildCount());
This always prints 0. Good.

At the bottom of the createNodes method it does it again:
System.out.println("Bottom of create nodes method " + top.getChildCount());
Always prints either 1 or 47, the correct numbers.

Then I created a method to just hold
tree.removeAll();
top.removeAllChildren();
and made a button to run it. When you push the remove button it does this:
System.out.println("Remove method " + top.getChildCount());
Always prints 0.

When you change the children of the top node you have to close and reopen it to see the difference. After setting to 0 children the top node shows no children when it is reopened. However, if you set the top node to have 1 child at first, then rerun the createNodes method to give it 47 nodes, though it prints "47" when you reopen the node it only has 1 node. If you start out with the 47 and change to the 1 it still has 47 nodes.

What's going on?
Rebecca
 
Rebecca Witmer
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer is, after you change the nodes you have to say:

((DefaultTreeModel)tree.getModel()). //line continues
nodeStructureChanged((DefaultMutableTreeNode)top);

That makes it realize that its nodes have changed. Wow. That was a very easy answer that took 5 hours to figure out.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!