简体   繁体   中英

How do I clear a JTree model?(Removing all nodes)

So this is a method of mine that is called everytime a new node is added.I need the model cleared everytime.The DefaultListModel has a .clear() method.The DefaultTreeModel does not.Help?

    public void fillUserList(){

    List<User> userFriends = ClientController.getInstance().getPrieteniiUserului(user);

    for(int i=0;i<userFriends.size();i++){
        User user = userFriends.get(i);

        model.insertNodeInto(new DefaultMutableTreeNode(user.getNume()), root, i);

    }

    System.out.println(userFriends);

}

I worked it out.The new code looks like this.

public void fillUserList(){    
    List<User> userFriends = ClientController.getInstance().getPrieteniiUserului(user);
    root.removeAllChildren(); //this removes all nodes
    model.reload(); //this notifies the listeners and changes the GUI
    for(int i=0;i<userFriends.size();i++){
        User user = userFriends.get(i);
        model.insertNodeInto(new DefaultMutableTreeNode(user.getNume()), root, i);        
    }
}

If you actually need to delete ALL nodes including root node you should make model null. Like this:

mytree.setModel(null)
public void clearTree(JTree tree) {
        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
        root.removeAllChildren();
        model.reload();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM