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

why pointer is not used in java?

3 Answers  


What are the important features of Java 9 release?

0 Answers  


what is the difference between multitasking and multithreading?

21 Answers   TCS,


What is float in java?

0 Answers  


Explain about main thread in java?

0 Answers  






What is the difference between array list and vector in java?

0 Answers  


Is vector ordered in java?

0 Answers  


What interface is extended by awt event listeners?

0 Answers  


What is a JAR file?

0 Answers  


Can we add default constructor to Servlet?

1 Answers   Fidelity,


What is the console in java?

0 Answers  


What does localhost mean?

0 Answers  


Categories