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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.