Populating JTree from database

别来无恙 提交于 2019-12-06 02:21:27

问题


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?


回答1:


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. :)



来源:https://stackoverflow.com/questions/5072072/populating-jtree-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!