Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

model

jtree

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);

}
like image 840
Adrian Stamin Avatar asked Oct 02 '12 20:10

Adrian Stamin


2 Answers

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);        
    }
}
like image 158
Adrian Stamin Avatar answered Sep 19 '22 03:09

Adrian Stamin


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

mytree.setModel(null)
like image 31
drvisor Avatar answered Sep 19 '22 03:09

drvisor