我有一个包含字段 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);
}
}
我如何编写那些注释指令?
最佳答案
使用DefaultMutableTreeNode创建你的节点
制作 ID 到节点的映射 - 当您从数据库中获取节点时,将它们以 ID 作为键存储在映射中。
一旦您拥有所有节点,再次遍历它们并匹配它们的父 ID,从 map 中检索它们。
假设您的树在数据库中的结构是正确的,它在这里也是正确的。选择任何节点并跟随父链到根。
使用根对象,您可以创建您的 JTree。 :)
关于java - 从数据库填充 JTree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5072072/