0

我正在尝试根据数据库结果集生成 JTree。我明白了

Category | Name
-------- | ----
   A     |  1
   B     |  2
   A     |  3

从数据库。如何仅在需要时将类别添加到 JTree?我希望树看起来像:

[Root]
    [Category A]
         Child 1
         Child 3
    [Category B]
         Child 2             

这是我到目前为止所拥有的:

    //Get the blueprints
    SqlHelper shelp = new SqlHelper();
    ArrayList<BaseInformation> bpList = shelp.getBlueprints();

    //Add each to model
    for(int x = 0; x < bpList.size(); x++){
        BaseInformation info = bpList.get(x);
        category = new DefaultMutableTreeNode(info.blueprintCategory);
        top.add(category);
        category.add(new DefaultMutableTreeNode(info.blueprintName));
    }

    JTree tree = new JTree(top);

    TreeModel model = tree.getModel();

    return model;
4

1 回答 1

0

好吧,您可以从树的根节点开始进行搜索,以检查是否存在类别。如果你的树和你的例子一样浅,简单地迭代根节点的 children() 可能就足够了,但是 DefaultMutableTreeNode 也有广度优先和深度优先的枚举。

如果这太慢(如果您的树非常大或嵌套很深),您还可以维护一个单独的类别映射到它们的树节点并以这种方式查找它们。无论哪种方式,如果找不到某个类别的现有节点,则创建并添加一个新节点,否则重新使用找到的节点。

于 2010-07-12T22:07:20.470 回答