我在滚动窗格中有一个静态jtree。现在我试图将child添加到jtree,它已成功添加。现在,添加的节点在jtree中不可见。
尝试1:我尝试过使用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();
尝试2:我也尝试过使用tree.setModel()
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);
即使这样,新添加的孩子也不可见。但它被添加到thr树中。我通过打印孩子来测试。 建议我一个解决方案。
答案 0 :(得分:2)
只需尝试以下行:
model.reload();
检查这个简单的例子。它适用于我,并在5秒延迟后显示两个新节点。
/**
* @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));
}
答案 1 :(得分:0)
我想也许你忘记在TreeNode的插入方法中设置你的新Node的父...这里是我的代码
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;
}