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

What’s meant by anonymous class?

0 Answers  


How does the java compiler work?

0 Answers  


Can a constructor be protected?

0 Answers  


What does java final mean?

0 Answers  


How a variable is stored in memory?

0 Answers  


what is anonymous class in java?

0 Answers  


what release of java technology are currently available what do they contain?

1 Answers  


What is the file type?

0 Answers  


Can we create an object of private class?

0 Answers  


In method overloading ,if i change the return type to Long instead of INT,is the program execute

6 Answers   HCL,


Explain all java features with real time examples

0 Answers  


What is arraylist e?

0 Answers  


Categories