Forum Stats

  • 3,757,128 Users
  • 2,251,200 Discussions


how to get everything in DefaultTreeNode

843806 Member Posts: 49,998
edited Jan 26, 2009 1:17AM in Swing
How do I get everything include the child of a child of a child of the root?

I'm using the as an example. Using the DefaultMutableTreeNode, top, I want to be able to get everything including all the books by calling one method with top as either the object or the parameter. how can I do this?


  • 800346
    800346 Member Posts: 1,094
    We can walk through the JTree recursively, something like this:
        public void traverse(JTree tree) {
            TreeModel model = tree.getModel();
            Object root;
            if (model != null) {
                root = model.getRoot();
            } else{
                System.out.println("Tree is empty.");
        protected void walk(TreeModel model, Object o){
            int  cc;
            cc = model.getChildCount(o);
            for( int i=0; i < cc; i++) {
                DefaultMutableTreeNode child = (DefaultMutableTreeNode) model.getChild(o, i );
                if (model.isLeaf(child) ){
                }else {
                    walk(model,child );
  • 843806
    843806 Member Posts: 49,998
    Hello. I actually wanted to get everything from the DefaultMutableTreeNode like an enumeration cuz i thought that all elements inside that class are stored in a private array built in that class, or something like that. I thought there would be a method that would save me a lot of processing time since everytime i walk through it, I access the database and it takes up a lot of time. I actually have that code but since you already did it for me with the using of extracting the TreeModel from JTree, I think it would save me a lot of time aside from connecting to the database for each node. Thanks a lot.
This discussion has been closed.