How to add and remove nodes in Jtree?



How to add and remove nodes in Jtree?..

Answer / yuvaraaj

You have a couple of choices:

Update the model directly:

DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
model.insertNodeInto(new DefaultMutableTreeNode("another_child"), root, root.getChildCount());
Update the tree nodes and then notify the model:

DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode)model.getRoot();
root.add(new DefaultMutableTreeNode("another_child"));
model.reload(root);
The same applies for removing nodes.

The DefaultTreeModel has a removeNodeFromParent(...) which will update the model directly.

Or you can use the remove(...) method of the DefaultMutableTreeNode class. In which case you would need to do the reload().

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More Core Java Interview Questions

Infinite loop using while ?

4 Answers  


Why string is not thread safe?

0 Answers  


When will you define a method as static in Java?

0 Answers   SwanSoft Technologies,


Explain Big-O notation with an example

1 Answers  


What is a resource leak ?

1 Answers  






Difference between Applet & Application?

6 Answers  


What are the advantages of the model over the event- inheritance model?

1 Answers  


Explain java coding standards for constants?

0 Answers  


What is this keyword in java?

0 Answers  


Is it possible to write a regular expression to check if string is a number?

0 Answers  


What does substring mean?

0 Answers  


When a lot of changes are required in data, which one should be a preference to be used? String or stringbuffer?

0 Answers  


Categories