Search code examples
javaswingjtree

How to remove grandchild from JTree?


My current JTree is set up as follows

  • Root
  • Child 1
    • Grandchild 1.1
    • Grandchild 1.2
  • Child 2
    • Grandchild 2.1
    • Grandchild 2.2

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


Solution

  • 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