Hi!

There is JTree component that I want to fill from the database. New nodes can be dynamically added to this tree. I need a procedure that will recursively traverse a tree. My problem is that all nodes are added to the root node, and sub-trees are not created. I've included System.out.println and it shows correct results. So, I just need to know how to add a new node to the correct parent node. Below is my code:

public static void createTree() {
        Vector ofTitles = new Vector();
        ofTitles = returnDataFromSelectQuery("select title from Folders");
        Object hierarchy[] = ofTitles.toArray();

        Vector ofChildOf = new Vector();
        ofChildOf = returnDataFromSelectQuery("select childOf from Folders");
        Object hierarchyChildOf[] = ofChildOf.toArray();

        tree1 = new JTree();
        tree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        node = new DefaultMutableTreeNode(hierarchy[0]);
        root = traverse( hierarchy, hierarchyChildOf, 0 );
        treeModel = (DefaultTreeModel)tree1.getModel();
        treeModel.setRoot(root);
...
}
public static DefaultMutableTreeNode traverse( Object hierarchy[], Object hierarchyChildOf[], int k ) {
        for(int i = 0; i < hierarchy.length; i++) {
          if (hierarchy[k].equals(hierarchyChildOf[i])) {
             System.out.println( hierarchy[i] + ", " + hierarchyChildOf[i]);
             DefaultMutableTreeNode child = new DefaultMutableTreeNode(hierarchy[i]);
             node.add(child);
             traverse(hierarchy, hierarchyChildOf, i);
          }
        }
        return (node);
    }

Thank you!

public static DefaultMutableTreeNode traverse( Object hierarchy[], Object hierarchyChildOf[], int k ) {
        for(int i = 0; i < hierarchy.length; i++) {
          if (hierarchy[k].equals(hierarchyChildOf[i])) {
             System.out.println( hierarchy[i] + ", " + hierarchyChildOf[i]);
             DefaultMutableTreeNode child = new DefaultMutableTreeNode(hierarchy[i]);
             node.add(child);
             traverse(hierarchy, hierarchyChildOf, i);
          }
        }
        return (node);
    }

I don't know where you're getting Node from, but it never changes in this method, so whatever it is when it comes in (root, I guess) is what it'll be coming out.

You probably want to pass the node you just added to the next call to traverse(), so it'll add the next nodes as children to it. There may be other flaws here, I'm very tired and if there's anything else I should be catching, I'm not, so another problem might turn up.

Thanks.

I've updated my code:

"    public static void traverse( Object hierarchy[], Object hierarchyChildOf[], int k ) {
        for(int i = 0; i < hierarchy.length; i++) {
          if (hierarchy[k].equals(hierarchyChildOf[i])) {
             MutableTreeNode childNode = new DefaultMutableTreeNode(hierarchy[i]);
             try {
                TreePath path = tree1.getNextMatch(hierarchyChildOf[i].toString(), 0, Position.Bias.Forward);
                if (path != null) {
                  MutableTreeNode parentNode = (DefaultMutableTreeNode)(MutableTreeNode) path.getLastPathComponent();
                  treeModel.insertNodeInto(childNode, parentNode, parentNode.getChildCount());
                  System.out.println("The child node " + hierarchy[i] + " is added to the parent node " + hierarchyChildOf[i]);
                }  else {
                    System.out.println("The path to the parent node " + hierarchyChildOf[i] + " cannot be found.");
                }
             } catch (Exception e) {
                e.printStackTrace();
             }
             traverse(hierarchy, hierarchyChildOf, i);
          }
        }
    }
public static void createTree() {
...
        tree1 = new JTree();        tree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        root = new DefaultMutableTreeNode(hierarchy[0]);
        treeModel = (DefaultTreeModel)tree1.getModel();
        treeModel.setRoot(root);
        traverse( hierarchy, hierarchyChildOf, 0 );
...
}

The code produces the following outputs:

The child node Contracts is added to the parent node Documents
The child node Correspondence is added to the parent node Documents
The path to the parent node Correspondence cannot be found.
The path to the parent node Correspondence cannot be found.
The child node Inner documents is added to the parent node Documents
The child node Labour contracts is added to the parent node Documents

So, as you may see, only children of the node "Documents" are added to the tree. Why actually the path to "Correspondence" cannot be found?

Well, probably my question is a bit unclear. I want to ADD nodes to the JTree, and not to search them.

Initially, I have a data set stored in the database and a BLANK JTree. This data set contains a tree structure, e.g.:
1. Documents
1.1 Correspondence
1.1.1 Incoming
1.1.2 Outgoing
1.2 Contracts
etc.

What I need, is to build the JTree based on the above-shown information. As you may see from my previous post, only second-level nodes are added to the root node, while the others are lost.

Could anybody suggest what is wrong in my code? Thanks!

Please, help me to find the error!!! I really cannot make my code working properly!

I'm sorry, I'm not really making a lot of sense of your code at the moment. Might be I need more coffee.

Anyway, it looks a little more complicated than maybe it needs to be. To populate a JTree from a recursive hierarchy, you need to call a populate() method, with a parameter (Node current, TreeNode currentTreeNode)
For for each descendant of current, the method will
- make a TreeNode (either DefaultMutable or your own flavor) for the descendant
- add that to currentTreeNode
- call populate (descendant, newTreeNode)

This should mirror whatever hierarchy you're reading. Maybe this will help you fix whatever problem you're having - I suspect that you're overcomplicating it, and that's where you problem is coming from.
If you're still having trouble, maybe you can give some color commentary on your code. Start with the formal parameters to traverse - what is each of these for?

Thank you. I'll try to be more specific.

There are two arrays filled from DB:
* hierarchy[]: Documents, Correspondence, Incoming, Outgoing, Contracts
* hierarchyChildOf[]: null, Documents, Correspondence, Correspondence, Documents

For instance, hierarchy[1] (Correspondence) is a child of hierarchyChildOf[2] (Documents). Now I must populate JTree with these data. The task is just to add all nodes defined in hierarchy[] to corresponding parent nodes specified in hierarchyChildOf[].

Below you may find my comments on the code:

public static void traverse( Object hierarchy[], Object hierarchyChildOf[], int k ) {
  for(int i = 0; i < hierarchy.length; i++) {
// We are searching children of hierarchy[k].
// If hierarchy[k] is equal to hierarchyChildOf[i], then it means that
// hierarchy[i] is a child of hierarchy[k]
    if (hierarchy[k].equals(hierarchyChildOf[i])) {
      MutableTreeNode childNode = new DefaultMutableTreeNode(hierarchy[i]);
      try {
// We are searching the node hierarchyChildOf[i] in the JTree->tree1
         TreePath path = tree1.getNextMatch(hierarchyChildOf[i].toString(), 0, Position.Bias.Forward);
         if (path != null) {
// If such node exists, then the childNode hierarchy[i] is added 
// to the parentNode hierarchyChildOf[i]
             MutableTreeNode parentNode = (DefaultMutableTreeNode)(MutableTreeNode)  path.getLastPathComponent();
             treeModel.insertNodeInto(childNode, parentNode, parentNode.getChildCount());
             System.out.println("The child node " + hierarchy[i] + " is added to the parent node " + hierarchyChildOf[i]);
         } else {
             System.out.println("The path to the parent node " + hierarchyChildOf[i] + " cannot be found.");
         }
      } catch (Exception e) {
             e.printStackTrace();
      }
     traverse(hierarchy, hierarchyChildOf, i);
   }
 }
}

Any ideas how to implement it correctly?

I solved the problem in the following way:

Hashtable h = new Hashtable();
        for (int i = 0; i < hierarchy.length; i++) {
           Hashtable child = new Hashtable();
           for(int j = 0; j < hierarchy.length; j++) {
              if (hierarchy[i].equals(hierarchyChildOf[j])) {
                  child.put(hierarchy[j],hierarchy[j]);
              }
           }
           if (!child.isEmpty()) h.put(hierarchy[i], child);
        }

        tree1 = new JTree(h);

So, your idea about populating JTree was very useful. Thanks!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.