java - 带表单生成器的 JTree

标签 java swing jtree removeall defaulttreemodel

我使用默认的 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/

相关文章:

java - 尝试使用 Spring Security 自定义失败登录

java - 有没有一种有效的方法通过java程序裁剪PDF并另存为图像(.JPG)?

java - 将 JTable 编辑保存到二维数组

java - 从 JTree 获取节点值并使用 JButton 将其显示在 JTable 中

Java - JTree UpdateUI 无法在 Runnable Jar 中工作

java - 二叉树到JTree?

java - JLabel.setText() 方法

java - 列出 AlarmManager 中的所有 PendingIntents

java - 检查 '0000-00-00' 的时间戳,无需转换

相当于 OpenLayers 的 Java