Roman Rdgz
Roman Rdgz

Reputation: 13294

How to remove all nodes from a JTree

I want to remove every node from a JTree, excepto the root node which I want to keep. I'm trying with a recursive method:

public void removeMeasurement (Long ID){
    removeMeasurement(root, ID);
    collapseAll();
    expandAll();
}

public void removeMeasurement (MutableTreeNode nodo, Long ID){      
    if (nodo.getChildCount() >= 0) { 
        for (Enumeration e=nodo.children(); e.hasMoreElements(); ) { 
            MutableTreeNode n = (MutableTreeNode)e.nextElement(); 
            removeMeasurement(n, ID); 
        } 
    }
    if(ID==0){
        nodo.removeFromParent();
        Register.debug("Eliminando ["+nodo.toString()+"]");
        return;
    }
    else if(nodo.toString().toLowerCase().equals("curve "+ID)){
        nodo.removeFromParent();
        return;
    }
}

So, my Tree has some nodes called "curve "+some ID, and I want to erase one of them and all its children with this method, but if I call the method with ID=0 I want it to remove every node from the JTree.

It is not working. It does erase the nodes, but when I add a node, the erased ones also appear with the new one. If it is the same node it was erased, it now appears twice. What's wrong?

NOTE: Each time I add or erase a node, I'm calling an update method for the JTree, to manually refresh it. It's there where I'm calling the shown methods to erase every node, so I can add the ones which are supposed to stay then.

Upvotes: 2

Views: 7343

Answers (1)

Luismahou
Luismahou

Reputation: 654

From my understanding you want to do is to remove the node whose ID is equal to the given ID, is that right? Then, I would recommend you to create a method, that given an ID, finds the node, and then another method to remove the found node. Something like this (I'm assuming that you're using a DefaultTreeModel, and DefaultMutableTreeNodes):

DefaultMutableTreeNode findById(TreeModel treeModel, Long id) {
  if (id == 0) {
    return (DefaultMutableTreeNode) treeModel.getRoot();
  }
  String curveId = "curve " + id;
  // The enumeration returns all the nodes, so it's not necessary to do a recursive search 
  Enumeration en = ((DefaultMutableTreeNode) treeModel.getRoot()).breadthFirstEnumeration();
  while (en.hasMoreElements()) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) en.nextElement();
    if (curveId.equalsIgnoreCase(node.toString()) {
      return node;
    }
  }   
}
void removeById(DefaultTreeModel treeModel, Long id) {
  DefaultMutableTreeNode nodeToRemove = findById(treeModel, id);
  if (nodeToRemove != null) {
    if (nodeToRemove.isRoot()) {
      nodeToRemove.removeAllChildren();
      treeModel.nodeStructuredChanged(nodeToRemove); // To notify the JTree to update from the root
    }
    else {
      treeModel.removeNodeFromParent(nodeToRemove); // Automatically notify the JTree
    }
  }
} 

Upvotes: 4

Related Questions