Reputation: 22210
I am developing a small desktop application in Net beans. I drag and drop a JTree
on my JFrame
and now i want to fill the node hierarchy of this this JTree
dynamically. For this i wrote a method which return me DefaultMutableTreeNode
object. Now i again create tree with this object but the tree still shows old (default) nodes:
DefaultMutableTreeNode root = createJTreeNodes();
jTree1 = new JTree(root);
jTree1.repaint();
jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
Could any one guide that what i need to change, in order to populate tree dynamically?
Upvotes: 0
Views: 301
Reputation: 4846
First you need to remove all the nodes in JTree which are added by netbeans by default.
DefaultTreeModel model=(DefaultTreeModel)jTree1.getModel();
model.setRoot(null);
Now create new root and add all the elements you want and use the above code to set the new root.
Upvotes: 0
Reputation: 324207
Could any one guide that what i need to change, in order to populate tree dynamically?
A couple of different options:
DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode)model.getRoot();
root.add(new DefaultMutableTreeNode("another_child"));
model.reload(root);
or
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
model.insertNodeInto(new DefaultMutableTreeNode("another_child"), root, root.getChildCount());
Upvotes: 3