开发者

JTree check for duplicate categories

I'm trying to generate a JTree based on a database result set. I get

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

from the database. How can I add the category to the JTree only if needed? I'd like the tree to look like:

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

This is what I have so far:

    //Get the blueprints
    SqlHelper shelp = new SqlHelper();
    ArrayList<BaseIn开发者_开发百科formation> 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;


Well, you could do a search starting from the root node of your tree to check for existence of a category. If your tree is as shallow as your example, simply iterating over the root node's children() is probably enough, but DefaultMutableTreeNode also has breadth- and depth-first enumerations.

If that is too slow (if your tree is very large or nested deeply), you could also maintain a separate map of categories to their tree nodes and look them up that way. Either way, if you can't find an existing node for a category, you create and add a new node, otherwise re-use what was found.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜