CDX
CDX

Reputation: 45

How to remove grandchild from JTree?

My current JTree is set up as follows

Question is, how can I remove any of the selected Grandchild? When I tried root.removeNodeFromParent(...), it seems like it only works for Child 1 and Child 2 and not the Grandchild.

DefaultTreeModel model = (DefaultTreeModel) workspaceTree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
DefaultMutableTreeNode child = (DefaultMutableTreeNode) root.getChildAt(0);
child.remove(new DefaultMutableTreeNode("Grandchild 1.1"));
model.reload(root);

I'm having this error saying Argument as a child

Upvotes: 0

Views: 320

Answers (1)

JB Nizet
JB Nizet

Reputation: 691655

Use DefaultTreeModel.removeNodeFromParent()

public void removeNodeFromParent(MutableTreeNode node)

Message this to remove node from its parent. This will message nodesWereRemoved to create the appropriate event. This is the preferred way to remove a node as it handles the event creation for you.

For example :

DefaultMutableTreeNode grandChild = (DefaultMutableTreeNode) child.getChildAt(0);
model.removeNodeFromParent(grandChild);
// no need to reload the root

Upvotes: 2

Related Questions