从数据库填充JTree [英] Populating JTree from database

查看:62
本文介绍了从数据库填充JTree的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,其中包含category_id,category_name和parent_category_id字段.而且parent_category_id具有category_id中代表父子关系的值.我没有固定的层次结构级别,它可以上升到5层或10层,对此没有限制..我需要一个代码来实现JTree以使事情对我有用.我应该也可以在菜单栏上实现相同的功能.请为此提供帮助.

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?

推荐答案

使用创建到节点的ID映射-当您从数据库中获取节点时,将其存储在以ID为键的映射中.

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.

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

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.

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

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

这篇关于从数据库填充JTree的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆