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

Describe 2 different ways to concatenate two strings.

0 Answers   TCS,


Can classes declared using the abstract keyword cab be instantiated?

0 Answers   MCN Solutions,


What is the use of jtable?

0 Answers  


How core java/j2ee project performance can be measured ?

1 Answers  


Explain about serializable interface in java?

0 Answers  






What the difference is between execute, execute Query, execute Update?

0 Answers  


Can I uninstall java?

0 Answers  


why java is platform independent?

5 Answers   IBM, SparkTG,


What are different data structures in java?

0 Answers  


what is mutual exclusion? : Java thread

0 Answers  


What was java originally called?

0 Answers  


Why local variables are stored in stack?

0 Answers  


Categories