Tactical Downvote
Tactical Downvote

Reputation: 2393

TreeNode shows only on Child. Why?

Hello i use following code. Every time actionPerformed is called the selected node gets a new child node. However JTree shows only one child per node although it has more. Why is that?

private class SomeActionListener implements ActionListener{

    private DefaultMutableTreeNode _root = new DefaultMutableTreeNode("ROOT");
    private JTree _tree;

    new SomeActionListener(){
        this._tree = new JTree(this._root);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)_tree.getSelectionPath().getLastPathComponent();
        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(e.getWhen());
        selectedNode.add(newNode);
    }
}

Upvotes: 0

Views: 74

Answers (3)

Syed Muhammad Humayun
Syed Muhammad Humayun

Reputation: 459

Try following, right after you add, update or remove a node:

this._tree.revalidate();
this._tree.repaint();

Upvotes: 0

luke657
luke657

Reputation: 835

You have to reload the tree model after adding the new node:

((DefaultTreeModel)(_tree.getModel())).reload();

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692181

Because you don't fire any event to inform the tree that the model has changed.

Get the tree model and call insertNodeInto(), and not only will the node be inserted, but an event will be sent to the JTree from the tree model to inform it that a node has been inserted, and that the view must be updated accordingly.

Upvotes: 3

Related Questions