java - 从数据库填充 JTree

标签 java mysql swing jtree

我有一个包含字段 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/

相关文章:

java - 脚本和Java : How can i say to Java to put the output file into a new folder?

Java:如何在子类中填充变量?

java - 我们可以使用 mockito 模拟 spy 对象吗?

java - 使用 ActionMap 的 JFrame 键盘快捷键?

java - 在 paint 方法中调用时 JLabel 不显示

java - Spring错误-org.springframework.beans.factory.NoSuchBeanDefinitionException

mysql - SQL 仅选择列上具有最大值的行

mysql - 如何在 MySQL 过程中使用 OUT 参数/通过 SELECT from table 读取数据

php - 在实时 Windows 服务器上安装 Wordpress?

java - 将 JLabel 添加到 JPanel,将 JPanel 添加到 JFrame