• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to dynamically add Nodes to JTree?

 
Jon Campbell
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can add nodes to my JTree, but after expanding a node, I can not add any child nodes to that node, or at least they dont show on the screen? Actually I can use the .add(new DefaultMutableTreeNode("Label")); to add a node to a parent node, but the new child node doesn't show on the display of the JTree?

Any help appreciated,
Jon
 
Paul Clapham
Sheriff
Posts: 21416
33
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After you add a child to a node, you have to tell the tree model that you did that so that it can get the display changed. If you're using a DefaultTreeModel then you call its nodesWereInserted() method to do that.
 
Brian Cole
Author
Ranch Hand
Posts: 908
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're using DefaultTreeModel then don't call
parentNode.add(newChild), but instead do
yourModel.insertNodeInto(newChild, parentNode, index)
and it will fire the events for you.

The downside is that you must supply the index.
If you want it to be the last child use
parentNode.getChildCount() as the index.

If you're not using DefaultTreeModel, then you
have to fire the events manually.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic