aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes How to dynamically add Nodes to JTree? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "How to dynamically add Nodes to JTree?" Watch "How to dynamically add Nodes to JTree?" New topic
Author

How to dynamically add Nodes to JTree?

Jon Campbell
Greenhorn

Joined: Nov 21, 2006
Posts: 5
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
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

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

Joined: Sep 20, 2005
Posts: 862
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.


bitguru blog
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to dynamically add Nodes to JTree?