Search code examples
javaobjectarraylistjtree

Java Object Array to JTree


I have a

Class Category 
private Category parent;
private String name;
private ArrayList<Category> categories;
private DefaultMutableTreeNode node;

and an

ArrayList<Category> categories

the ArrayList contains

[0]Categorie #1
   parent = null
   name = asdasd
   ArrayList<Category> categories
      [0]Categorie #2
          parent = #1
          name = asdasddsa
          ArrayList<Category> categories
              [0]Categories #4
                  parent = #2 
                  name = asdasdasd
                  ArrayList<Category> categories = null
      [1]Categorie #3
          parent = #1
          name = asdasdasdasdasd
          ArrayList<Category> categories = null

and i want to create a JTree out of that ArrayList. I tried it with a function that uses itself until the categories ArrayList was null but with this method i couldn't have more than 1 category in the parent categorie.

I created these functions but they don't work.

public void generateNodes(Category category,DefaultMutableTreeNode root){
    ArrayList<Use> usages = category.getUsages();
    for(Use use: usages){
        category.getNode().add(use.getNode());
    }
    if(!category.getCategories().isEmpty()){
        root.add(category.getNode());

        for(Category cat: category.getCategories()){
            generateNodes(cat, category.getNode());
        }

    }else{
        root.add(category.getNode());
    }

}

Solution

  • You just need to create a recursive method. Every Category you come across, create a DefaultMutableTreeNode, then add the properties as child nodes. Then recursively call method with the contained Cateogories.

    If you want to have more than one category as the root parent, you should make a 'fake' root node, then call this on JTree :

    setRootVisible(false);

    Its still one tree, but it looks like many. Is that what you meant?

    Your code should look something like this :

    public void generateNodes(Category categories,DefaultMutableTreeNode root){
            ArrayList<Use> usages = categ.getUsages();
            for(Use use: usages){
                categ.getNode().add(use.getNode());
            }
            if(!categ.getCategories().isEmpty()){
                root.add(categ.getNode());
    
                for(Category cat: categ.getCategories(){
                    generateNodes(categ, root);
                }
    
            }else{
                root.add(categ.getNode());
            }
    
    }