0

I am trying to add a node to my JTree. I do that like so:

    DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot();
    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(event.getObjectThatHasChanged());
    root.add(newNode);
    ((DefaultTreeModel) tree.getModel()).reload();

However, the tree itself doesnt update. Ive read posts that reload() is what you are supposed to call, but to no effect. Also please note this is being called on the EDT. Any ideas?

EDIT:

I have tried this approach:

    DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot();
    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(event.getObjectThatHasChanged());
    ((DefaultTreeModel) tree.getModel()).
            insertNodeInto(newNode, root, root.getChildCount() - 1);

Still no go. However, when I shut the program down and reopen it, the new node is there. (I persist my data).

user489041
  • 27,916
  • 55
  • 135
  • 204
  • For [example](http://stackoverflow.com/questions/22683092/jtree-avoid-collapse-after-reload/22683989#22683989) – MadProgrammer May 14 '15 at 22:07
  • @MadProgrammer You use `node.getChildCount())` where as copeg has `node.getChildCount() - 1)` in his example.Can you clarify which is correct? – user489041 May 15 '15 at 13:54
  • @user489041 Java is zero index, so the number of actual nodes is getChildCount - 1. So after you add a node tothe parent mode, you need to reference the last node... – MadProgrammer May 15 '15 at 20:36

1 Answers1

3

Add nodes to a JTree using the DefaultTreeModel's insertNodeInto method. To quote the API

This will then message nodesWereInserted to create the appropriate event. This is the preferred way to add children as it will create the appropriate event.

For example:

((DefaultTreeModel) tree.getModel()).insertNodeInto(newNode, root, 0);//inserts at beginning
//((DefaultTreeModel) tree.getModel()).insertNodeInto(newNode, root, root.getChildCount() - 1);//inserts at end
copeg
  • 8,290
  • 19
  • 28
  • I tried this approach, but to no avail. Does the tree perhaps need repainted or revalidated? – user489041 May 14 '15 at 19:54
  • 1
    Shouldn't be necessary. Can you post an [MCVE](http://stackoverflow.com/help/mcve) that demonstrates this not working? – copeg May 14 '15 at 20:04