我使用默认的 NetBeans 编辑器创建了一个表单,并在其上放置了一个 jTree
。
然后它以某种方式在其中创建了一堆元素,例如“颜色”、“运动”、“食物”。但它不在创建代码中。它来自哪里以及如何编辑它...
即使我执行jTree1.removeAll();
,一切仍然存在......并且我的用于向 jTree 添加新项目的代码不起作用。
private void test(java.awt.event.MouseEvent evt) {
//trying to remove all, but it does not remove anything
jTree1.removeAll();
//it does print it in debug meaning that this function is called
System.out.println("qwe");
//create the root node
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
//create the child nodes
DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");
//add the child nodes to the root node
root.add(child1);
root.add(child2);
//now how do I add it to the tree?
//???
}
我需要能够在运行时编辑 jTree
内容。
最佳答案
接下来的问题是,您创建像这样的 JTree
JTree tree = new JTree()
(根据 docs )它有示例节点。创建节点(root、child1、child2)后添加下一行,一切都会正常工作:
DefaultTreeModel model =(DefaultTreeModel) jTree1.getModel();
model.setRoot(root);
您也不需要调用jTree1.removeAll();
它用于其他目的。( docs )
阅读 JTree
的教程
关于java - 带表单生成器的 JTree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58903755/