javaswingjtreejtreetable

Deleting node childs of a Java JTree structure


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?


Solution

  • 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.