Skip to content
Advertisement

Jtree not shown on adding a node!

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.

Advertisement

Answer

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));
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement