如何从数据库表中填充多级jtree [英] How to populate multilevel jtree from database table
问题描述
我有一个如下的数据库表。我想从表中制作动态jtree。
id姓名父母
1颜色null
2红色1
3白色1
4绿色1
5暗4
6光4
我尝试了什么:
要从数据库中检索表格,我已编写代码以下。
i have a database table like the following. I want to make dynamic jtree from the table.
id Name parent
1 color null
2 red 1
3 white 1
4 green 1
5 dark 4
6 light 4
What I have tried:
To retrieve the table from database i already written the code following.
while( rs.next() ) {
String parentId = rs.getString("node_Id");
String parentName = rs.getString("node_Name");
String paren = rs.getString("node_Parent");
int treeLvl = rs.getInt("node_Level");
// the above code is working perfectly fine, the problem start from here
Map<String, DefaultMutableTreeNode> parentsMap
= new HashMap<>();
DefaultTreeModel tbl = (DefaultTreeModel) TreePro.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode)tbl.getRoot();
DefaultMutableTreeNode Root = parentsMap.get(paren);
Root = new DefaultMutableTreeNode( paren );
parentsMap.put(parentId, Root );
root.add(Root);
DefaultMutableTreeNode parent = parentsMap.get(parentName);
parent = new DefaultMutableTreeNode( parentName );
parentsMap.put(parentId, parent );
Root.add(parent);
}
现在它创建了这样的jtree
Root
Null
-color
颜色
-red
颜色
-white
颜色
-green
green
-dark
绿色
-light
显然它错了,我怎样才能从数据库表中正确地生成jtree。现在我希望我以正确的方式建立我的问题
Now it's creates jtree like this
Root
Null
-color
color
-red
color
-white
color
-green
green
-dark
green
-light
Obviously its wrong, how can i make jtree correctly from database table. Now i do hope i established my question in correct way
推荐答案
每次在循环中重新创建根节点。您应该在开头创建一次根节点。然后使用循环将所有子条目添加到根节点。
You are recreating the root node each time in the loop. You should create the root node once at the beginning. Then use the loop to add all the child entries to the root node.
这篇关于如何从数据库表中填充多级jtree的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!