How to get all the paths of a JTree?

5

How can I get all the paths of a JTree including the nodes that have parents other than root?

root
  exemplo1
    exemplo1.1
  exemplo2
    exemplo2.1

If I do something like this:

for(int i = 0; i< tree.getRowCount(); i++){
   TreePath path = tree.getPathForRow(i);
   System.out.println(path);
}

output will be:

[root]
[root,exemplo1]
[root,exemplo2]

How can I access path or index of exemplo1.1 and exemplo2.1 ?

    
asked by anonymous 18.12.2014 / 14:52

2 answers

4

Only by completing the @renan response, you can also scan JTree like this:

private void outroMetodo() {
    List<Object[]> niveis = new ArrayList<>();
    DefaultMutableTreeNode raiz = (DefaultMutableTreeNode) theTree.getModel().getRoot();

    int index = 0;
    int posicao = 0;

    niveis.add(new Object[] { raiz, "", (int) 0 });
    index++;

    while (niveis.size() != 0) {
        DefaultMutableTreeNode no;
        do {
            Object[] nivel = niveis.get(posicao);
            no = (DefaultMutableTreeNode) nivel[0];

            System.out.printf("%s (%d)\n", nivel[1] + "--" + no.toString(), nivel[2]);

            Enumeration subNiveis = no.children();

            while (subNiveis.hasMoreElements()) {
                niveis.add(index++, new Object[] { subNiveis.nextElement(), nivel[1] + "--",  
                        (int) nivel[2] + 1});
            }

            niveis.remove(nivel);
            if (no.getChildCount() != 0) {
                index -= no.getChildCount();
            } else {
                index = 1;
            }
        } while (no != null && no.getChildCount() != 0);
    }
}

Basically, I used ArrayList to control the nodes, at each iteration I checked if the current node had children, if it had, child nodes were added below the current node and then the current node was removed from ArrayList and so the iteration continued until there were no more nodes.

In the array list of objects ( List<Object[]> niveis = new ArrayList<>(); ), the following items are used:

  • levels [0] - node to check.
  • levels [1] - text for level organization.
  • levels [2] - level within each node.

The result can be seen in the image below.

    
05.01.2015 / 17:24
5
  

How can I get all the paths of a JTree including the nodes it   have parents other than root?

I did a search and the logic to get access to all nodes is quite simple.

First, get root from your JTree using the getRoot method:

TreeModel theRoot = (TreeModel) tree.getModel().getRoot();

Next, just count how many child elements this root has, so there is the getChildCount method:

int childCount = tree.getModel().getChildCount(theRoot);

Having the number of child elements and root , just create a loop from 0 to the number of child elements, so you can access each index using the getChild method. p>

for(int i = 0; i < childCount; i++)
   System.out.println( tree.getModel().getChild(theRoot, i) ); // faz algo...


To access the nodes within the child elements, just do the same process:
- Count how many elements are internally
- Start a loop from 0 to the amount of elements.

  

How can I access the path or index of example1.1 and example2.1?

// Acessando o filho 'Exemplo1 -> 1'
String primeiro = tree.getModel().getChild(Exemplo1, 0).toString(); // O primeiro indice inicia-se em '0'

//Acessando o filho 'Exemplo2 -> 2'
String segundo = tree.getModel().getChild(Exemplo2, 0).toString();


I put a simple test code containing the same structure as JTree created by you in the question, follow the image:

Theexampleissimple:Itwillaccessthetwochildelements(Example1>1andExample2>2)andstorethenameinaString.Theoutputis:

12


importjavax.swing.JFrame;importjavax.swing.JTree;importjavax.swing.tree.DefaultMutableTreeNode;publicclassMyWindowextendsJFrame{publicMyWindow(){super("StackOverflow");
        init();
    }

    private void init(){
        // Propriedades do JFrame
        setSize(500, 500);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        DefaultMutableTreeNode theRoot = new DefaultMutableTreeNode("Root");

        DefaultMutableTreeNode theFirstExample = new DefaultMutableTreeNode("Exemplo1");
        DefaultMutableTreeNode firstExampleChild = new DefaultMutableTreeNode("1");
        theFirstExample.add(firstExampleChild);

        DefaultMutableTreeNode theSecondExample = new DefaultMutableTreeNode("Exemplo2");
        DefaultMutableTreeNode secondExampleChild = new DefaultMutableTreeNode("2");
        theSecondExample.add(secondExampleChild);

        theRoot.add(theFirstExample);
        theRoot.add(theSecondExample);

        JTree theTree = new JTree(theRoot);
        getContentPane().add(theTree);

        // Acessando o filho 'Exemplo1 -> 1'
        String exampleOne = theTree.getModel().getChild(theFirstExample, 0).toString();

        //Acessando o filho 'Exemplo2 -> 2'
        String exampleTwo = theTree.getModel().getChild(theSecondExample, 0).toString();

        System.out.println(exampleOne);
        System.out.println(exampleTwo);
    }

    public static void main(String[] args) {
        new MyWindow().setVisible(true);
    }
}
    
05.01.2015 / 07:30