从数据库填充 JTree

发布于 2024-10-18 06:14:15 字数 909 浏览 3 评论 0原文

我有一个包含字段category_id、category_name 和parent_category_id 的表。并且parent_category_id具有来自表示父子关系的category_id的值。我没有任何固定的层次结构级别,它可能高达 5 级或 10 级,并且没有限制。我需要一个代码来说明如何实现此 JTree 以使它为我工作。我应该也能够对菜单栏实现相同的功能。请帮我解决这个问题。

谷歌搜索后我发现了这个,

Map<String, Node> idToNode = new HashMap<String, Node>();   

//create nodes from ResultSet   
while ( resultSet.next() ){       
    Node node = //create node -contains info, parent id, and its own id from ResultSet
    //put node into idToNode, keyed with its id   
}   

//link together   
Iterator<String> it = idToNode.keySet().iterator();   
Node root = null;   
while ( it.hasNext() ){          
    Node node = idToNode.get(it.next());       
    Node parent = idToNode.get(node.getParentId());   
    if ( parent == null ) {  
        root = node;  
    }else{  
       parent.addChild(node);  
    }  
}

我如何对这些注释的指令进行编码?

I have a table with fields category_id, category_name and parent_category_id. And parent_category_id has values from category_id which represents the parent child relationship. I dont have any fixed level of hierarchy, it may go up to 5 levels or 10 levels and there is no limit to that.. I need a code for how to implement this JTree to make thing work for me. I should be able to implement the same for Menu bar as well.. Please help me with this..

After googling I found this,

Map<String, Node> idToNode = new HashMap<String, Node>();   

//create nodes from ResultSet   
while ( resultSet.next() ){       
    Node node = //create node -contains info, parent id, and its own id from ResultSet
    //put node into idToNode, keyed with its id   
}   

//link together   
Iterator<String> it = idToNode.keySet().iterator();   
Node root = null;   
while ( it.hasNext() ){          
    Node node = idToNode.get(it.next());       
    Node parent = idToNode.get(node.getParentId());   
    if ( parent == null ) {  
        root = node;  
    }else{  
       parent.addChild(node);  
    }  
}

How do i code those commented instructions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静若繁花 2024-10-25 06:14:15

使用 DefaultMutableTreeNode 创建

节点ID 到节点的映射 - 当您从数据库获取节点时,将它们存储在映射中,并以 id 作为键。

拥有所有节点后,再次遍历它们并匹配它们的父 ID,从地图中检索它们。

假设您的树在数据库中结构健全,那么它在这里也将是健全的。选择任意节点并跟随父链到根。

使用根对象,您可以创建 JTree。 :)

Use DefaultMutableTreeNode to create your nodes

Make a map of IDs to nodes - as you get your nodes from the database, store them in the map with the id as their key.

Once you have all your nodes, go through them once more and match their parent ids up, retrieving them from the map.

Assuming your tree is structurally sound in the database, it will be sound here. Pick any node and follow the parent chain the the root.

With the root object, you can create your JTree. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文