Jtree not shown on adding a node!

你。 提交于 2019-12-06 12:33:31

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));
}

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;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!