java 如何清除 JTree 模型?(删除所有节点)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12697650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:52:54  来源:igfitidea点击:

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

javamodelclearjtree

提问by Adrian Stamin

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?

所以这是我的一个方法,每次添加新节点时都会调用。我每次都需要清除模型。 DefaultListModel 有一个 .clear() 方法。DefaultTreeModel 没有。帮助?

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

}

采纳答案by Adrian Stamin

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

回答by drvisor

If you actually need to deleteALL nodes including rootnode you should make model null. Like this:

如果您确实需要删除包括根节点在内的所有节点,则应将模型设为空。像这样:

mytree.setModel(null)