954,536 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Setting the content of a JTree without creating a new object.

Hey everyone,

I was just wondering if there is a method as part of the JTree class that would accept a parameter such as an instance of DefaultMutableTreeNode and change the content of the tree with that tree node as the root. I am looking for a method of doing what you can do with the constructor of JTree when creating the object when you can dos omething such as the following...

DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
  DefaultMutableTreeNode folder = new DefaultMutableTreeNode("Folder");
    DefaultMutableTreeNode leaf = new DefaultMutableTreeNode("Leaf");
parent.add(leaf);
root.add(folder);

JTree myTree = new JTree(root);


So essentially I am looking for a method like the above contruction of the JTree myTree, but I don't want to have to keep constructing a new object every time I want to change the content of the tree, as to keep the same properties of the JTree such as selection listeners etc.

If no such method exists can anyone suggest a way of doing this?

Thanks,
Jonathon.

bops
Posting Whiz in Training
214 posts since Aug 2005
Reputation Points: 23
Solved Threads: 5
 

That constructor creates a new JTree with a DefaultTreeModel based upon the root node you supply. If you wish to modify the tree, you can either modify the contents of that tree model directly (by adding or removing nodes wherever you like) or you can construct a new TreeModel and set the JTree to use that model instead with JTree.setModel(javax.swing.tree.TreeModel) .

This tutorial on How to Use Trees might be helpful.

Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You