How can I refresh a JTree after adding some nodes to the underlying model?

前端 未结 8 2098
情歌与酒
情歌与酒 2020-12-08 21:42

First of all, let me say that I dont use the DefaultTreeModel. I implement my own TreeModel, so i cant use the DefaultXXX stuff. The problem is this: Through some addStuff()

8条回答
  •  旧巷少年郎
    2020-12-08 22:32

    I also found implementing TreeModel a bit confusing when the tree consist of more than just Folders(root) and Files(child), so I've used the DefaultTreeModel. This works for me. The method creates or refreshes the JTree. Hope this helps.

        public void constructTree() {       
    
            DefaultMutableTreeNode root =
                    new DefaultMutableTreeNode(UbaEnv.DB_CONFIG);
            DefaultMutableTreeNode child = null;
    
            HashMap dbConfigs = env.getDbConfigs();
            Iterator it = dbConfigs.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry pair = (Map.Entry) it.next();
                child = new DefaultMutableTreeNode(pair.getKey());
    
                child.add(new DefaultMutableTreeNode(UbaEnv.PROP));
                child.add(new DefaultMutableTreeNode(UbaEnv.SQL));
                root.add(child);
            }
    
            if (tree == null) {
                tree = new JTree(new DefaultTreeModel(root));
                tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
                tree.addTreeSelectionListener(new TreeListener());
            } else {
                tree.setModel(new DefaultTreeModel(root));
            }
    }
    

提交回复
热议问题