Reputation: 45
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
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