JTree编辑根节点?

时间:2014-07-14 15:31:40

标签: java swing jtree treenode defaulttreemodel

我正在尝试创建一个我可以稍后编辑的JTree。到目前为止,我有以下代码,它按预期生成具有根节点的树。但是,当单击按钮(触发动作侦听器)时,它会在根节点下添加另一个节点。我宁愿它做的是修改根节点。反正有没有这样做?我试着改变各种论点;像0到-1,(MutableTreeNode)treeModel.getRoot()到(MutableTreeNode)treeModel等。

感谢您提供任何帮助。

//Set first as Defualt Node
final DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("You must log in first.");
final DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
tree_folderList = new JTree(treeModel);
tree_folderList.setEditable(true);
tree_folderList.setBorder(new BevelBorder(BevelBorder.LOWERED));
treescrollPane = new JScrollPane(tree_folderList);

tree_folderList.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree_folderList.setShowsRootHandles(true);
//treeModel.addTreeModelListener(new MyTreeModelListener());        

ActionListener btn_RefreshMail_Listener = new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        if (sessionkey == null || sessionkey.contains("Invalid")) {
            treeModel.insertNodeInto(new DefaultMutableTreeNode("Must be logged in first."), (MutableTreeNode) treeModel.getRoot(), 0);
        }
        else {
            //txt_folderList.setText(DMD.getInbox(sessionkey));
            treeModel.insertNodeInto(new DefaultMutableTreeNode("Logged in."), rootNode, 0);
        }
    }
};

1 个答案:

答案 0 :(得分:2)

我使用以下代码。我希望这有助于其他人在解决同样的问题。秘诀是创建一个新的defaultnode然后使用setroot方法。

ActionListener btn_RefreshMail_Listener = new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        if (sessionkey == null || sessionkey.contains("Invalid")) {
            DefaultMutableTreeNode rootNode2 = new DefaultMutableTreeNode("You must log in first.");
            treeModel.setRoot(rootNode2);
            treeModel.reload();
        }
        else {
            //txt_folderList.setText(DMD.getInbox(sessionkey));
            DefaultMutableTreeNode rootNode2 = new DefaultMutableTreeNode("Logged in.");
            treeModel.setRoot(rootNode2);
            treeModel.reload();
        }
    }
};