How to add and remove nodes in Jtree?

Answer Posted / 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       View All Answers


Please Help Members By Posting Answers For Below Questions

How do you input a string in java?

610


How many return statement are allowed in a function?

550


Why does java doesnt suuport unsigned values?

1878


What does java ide mean?

731


Which number is denoted by leading zero in java?

905






Can we override protected method in java?

690


What is collection api?

707


What is preparedstatement in java?

662


Can we clone singleton class in java?

607


What technique can be employed to compare two strings?

686


Which package is used for pattern matching with regular expressions?

728


What is meant by inheritance and what are its advantages?

684


What is an object in java and how is it created?

685


What is difference between add() and addelement() in vector?

1165


What is Java Annotations?

633