Deleting node childs of a Java JTree structure

6.7k Views Asked by At

I have a ftp program that retrieve folder data each time expanded. It does this by using a model like this:


    private void FilesTreeTreeExpanded(javax.swing.event.TreeExpansionEvent evt) {
String path = new String("");

 DefaultMutableTreeNode chosen = (DefaultMutableTreeNode) evt.getPath().getLastPathComponent();

 String[] pathArray = evt.getPath().toString().replaceAll("]", "").split(",");
 for (int i = 1 ; i < pathArray.length ; i++) path += "/"+ pathArray[i].trim();

// i were aded chosen.removeAllChildren(); without success ftp.GoTo(path);

ArrayList listDir = null; listDir = ftp.ListDir(); ArrayList listFiles = null; listFiles = ftp.ListFiles(); DefaultMutableTreeNode child = null , dir = null , X = null; //this will add files to tree for (int i = 0; i < listFiles.size(); i++) { child = new DefaultMutableTreeNode(listFiles.get(i)); if(listFiles.size() > 0) model.insertNodeInto(child, chosen, 0); } //this will add dirs to list for (int i = 0; i < listDir.size(); i++) { X = new DirBranch("در حال دریافت اطلاعات ...").node(); dir = new DirBranch( (String) listDir.get(i)).node(); dir.add(X); if(listDir.size() > 0) model.insertNodeInto(dir, chosen, 0); } FilesTree.setModel(model); //this is my Swing JTree }

the problem is every time i expand the JTree it duplicate list of files and folders. so i tried to use chosen.removeAllChildren(); @ the top of the code but it didnt remove anything. what should i do?

3

There are 3 best solutions below

0
On BEST ANSWER

Your model is correct, but JTree is operating on old information.

The removeAllChildren() method removes the children, but it does not fire any events and the model.insertNodeInto() does fire insert events. So, JTree sees the nodes being added, but never sees the nodes being removed.

After adding the new children, try calling model.reload(chosen) to invalidate the tree below chosen.

Since you will be reloading the branch, you can also change model.insertNodeInto(dir, chosen,0) to chosen.insert(dir,0). That reduces the number of events posted.

0
On

In my application also i just fact the same problem. For that i just used the following code.

    JTree.removeAll();
    JTree.setModel(null);

It remove all child nodes from my Jtree.

1
On

Calling removeAllChildren() will remove the children from the node. There must be something else happening here that is creating duplicates. Make sure you are not calling anything twice and that you are refreshing the display of the tree.