Kyle
Kyle

Reputation: 2379

JTree Edit Root Node?

I am trying to create a JTree I can edit later. So far I have the following code which generates the tree with root node as expected. But, when the button is clicked (triggering the action listener) it adds another node under the root node. What I would rather it do is modify the root node. Is there anyway to do this? I tried changing the various arguments; like a 0 to -1, (MutableTreeNode) treeModel.getRoot() to (MutableTreeNode) treeModel, etc.

Thanks for any help with this.

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

Upvotes: 4

Views: 2896

Answers (1)

Kyle
Kyle

Reputation: 2379

I got it working with the following code. I hope this helps someone else struggling with the same problem. The secret was to create a new defaultnode and then use that with the setroot method.

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

Upvotes: 4

Related Questions