2

I have a static jtree in a scrollpane. And now iam trying to add child to jtree, it got added successfully. Now, the added node is not visible in the jtree.

Try 1: I have tried with model.reload()

DefaultTreeModel model = (DefaultTreeModel) (tree.getModel());
TreePath Path = findByName(tree, new String[]{Globals.CONS_UIAPROJECTS});
DefaultMutableTreeNode pnode = (DefaultMutableTreeNode) Path.getLastPathComponent();
model.insertNodeInto(UIAProjectExploreDisplay.nodeProTree, pnode, pnode.getChildCount());
model.reload();

Try 2: I have tried with tree.setModel() too...

DefaultTreeModel model = (DefaultTreeModel) (tree.getModel());
TreePath Path = findByName(tree, new String[]{Globals.CONS_UIAPROJECTS});
DefaultMutableTreeNode pnode = (DefaultMutableTreeNode) Path.getLastPathComponent();
model.insertNodeInto(UIAProjectExploreDisplay.nodeProTree, pnode, pnode.getChildCount());

DefaultTreeModel projectTreeModel = new DefaultTreeModel((DefaultMutabletreeNode) model.getRoot());
tree.setModel(projectTreeModel);

Even then newly added child is not visible. but Its getting added in thr tree. I tested by printing the child. Suggest me a solution.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
yogi
  • 266
  • 2
  • 11

2 Answers2

2

Simply try the following line:

model.reload();

Check this simple example. It works for me and shows both new nodes after the 5 seconds delay.

/**
 * @param args
 */
public static void main(String[] args) {
    TestTree frame= new TestTree();
    frame.setSize(400, 400);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.pack();
    MutableTreeNode root = (MutableTreeNode)tree.getModel().getRoot();
    System.out.println("A: "+root.getChildCount());     
    try {
        Thread.sleep(5000);
    }
    catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    root.insert(new DefaultMutableTreeNode("test"), 1);
    ((DefaultMutableTreeNode)root.getChildAt(2)).insert(new DefaultMutableTreeNode("test2"), 1);
    ((DefaultTreeModel)(tree.getModel())).reload();
    System.out.println("B: "+root.getChildCount());
    System.out.println(root.getChildAt(1));
}
grackkle
  • 776
  • 1
  • 9
  • 26
0

I think maybe you forget to set your new Node's parent in your TreeNode's insert method...here is my code

public void insert(MyTreeNode newChild, int childIndex) {
    if (!allowsChildren) {
        throw new IllegalStateException("node does not allow children");
    } else if (newChild == null) {
        throw new IllegalArgumentException("new child is null");
    }

        newChild.setParent(this);
        if (children == null) {
            children = new ArrayList<GoodSort>();
        }
        children.add(childIndex,(GoodSort)newChild);
        ((GoodSort)newChild).parent = this;
}
Nick Allen
  • 1,647
  • 14
  • 20