有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

运行时生成节点的java JTree

我的程序基于输入数据构建一棵树。在运行程序之前,无法知道应该创建多少节点以及节点的位置(在哪个父节点下)

使用JTree,如果事先知道结构,我们可以轻松地添加节点

例如

//create the root node
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
/create the child nodes
DefaultMutableTreeNode vegetableNode = new DefaultMutableTreeNode("Vegetables");
vegetableNode.add(new DefaultMutableTreeNode("Capsicum"));
vegetableNode.add(new DefaultMutableTreeNode("Carrot"));
vegetableNode.add(new DefaultMutableTreeNode("Tomato"));
vegetableNode.add(new DefaultMutableTreeNode("Potato"));
root.add(vegetableNode);

但是,一旦指定了根节点,我的树将以增量方式构建。因此,我希望我的JTree随时在特定的父节点下添加一个节点

请注意,树也将在递归方法中构建。这意味着主JTree对象应该在这个方法之外创建

树可能有多个层,这意味着从节点到叶子的路径可能需要10次跳跃

在运行时向只知道其父节点的JTree添加节点的最佳方式是什么

这里需要注意的是,当两个不同的父节点具有相同的名称时,例如,如果节点苹果应位于名为水果的节点下,但水果位于两个不同的路径中

root -> aaa -> bbb -> ccc -> fruit
root -> aaa -> fff -> ggg -> hhh -> fruit

共 (1) 个答案

  1. # 1 楼答案

    然后,您应该考虑提供自己的树模型

    引用JTree的Oracle tutorial

    One of the ways you can lazily load children of a Tree is by utilizing the TreeWillExpandListener interface. For example, you can declare and load root, grandparent and parent of a Tree along with the application as shown in the following code:

    根据OP的评论:DefaultMutableTreeNode不支持“名称”。这意味着:您需要以一种超级简单的方式自己实现,可能类似于:

    class MyTreeNode extends DefaultMutableTreeNode {
       private final String name;
    
       MyTreeNode(String name, ... whatever ) {
         ...
         SOME_NODE_REGISTRY.put(name, this);
       }
    

    然后您需要提供该注册表,可能作为某种单例映射实例。换句话说:您必须编写代码,A)允许您按名称存储节点,然后B)按名称识别/查找节点