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

3

8

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

}
Biller answered 2/10, 2012 at 20:19 Comment(2)
Did you try to use the root node, and use the removeAllChildren() method?Caudillo
It works.But I also needed the model.reload() called.Biller
B
5

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);        
    }
}
Biller answered 2/10, 2012 at 20:42 Comment(0)
Y
2

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

mytree.setModel(null)
Yacketyyak answered 20/6, 2013 at 5:51 Comment(0)
O
0
public void clearTree(JTree tree) {
        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
        root.removeAllChildren();
        model.reload();
    }
Oliy answered 10/6, 2022 at 11:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.