javaswingtreetreemodel

Java Custom Tree Model updating problem


Here is structure of the tree:

root -branches --leafs

I use for TreeModel DefaultTreeModel and my objects implement TreeNode interface

leaf is some Object:

public class Leaf implements TreeNode
{
   // implementation

branch has List of leafs:

public class Branch implements TreeNode
{
 private List<Leaf> leafs;

 // implementation

And root is container of branches:

public class Root implements TreeNode
{
  private List<Branch> branches;

  // implementation

When I add new leaf, my tree doesn't updated, when I add leaf and create new DefaultTreeModel with my root object it's updated. I watch DefaultMutableTreeNode implementation, there isn't any event firing on inserting childs... What am I doing wrong? Before, I tried to implement TreeModel interface wich looks much better then implementing TreeNode interface for three classes, but result was similar. I also read about GlazedLists, but I dislike their tree conception. For me, the best is implementation TreeModel interface conception, but how to update model when some inner List in model add new element?...


Solution

  • Without seeing the code, it's hard to be sure - nevertheless I'll bet on my guess: you don't notify the TreeModel about your insertions ;-)

    A code snippet of what you have to do if your node implementation is not of type MutableTreeNode:

     // do the parent wiring in your custom TreeNode
     int position = myBranch.addChild(node);
     // notify the model 
     model.nodesWhereInserted(myBranch, new int[] {pos}); 
    

    If it is of type MutableTreeNode, the easier way is via the convenience methods in DefaultTreeModel

     model.insertNodeInto(node, myBranch, position)