How to get all paths of a Jtree?

Asked

Viewed 639 times

5

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

root
  exemplo1
    exemplo1.1
  exemplo2
    exemplo2.1

If I do something like that:

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

The output will be:

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

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

  • @Renan Why the "reward" in a question you yourself answered? There are still doubts? I hope you get your answer :)

  • @But you threw the reward at 17:15 (UTC) and Matthew answered at 16:24 (UTC). I am confused.

  • @Although something like "1 new answer" or "2 new answers" always appears without refresh, it seems plausible, ok, I’m glad you found the solution, even more. + 1 in his reply

2 answers

5

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

I did some research and the logic to have access to all nodes is quite simple.

First, get the root of his JTree using the method getRoot:

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

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

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

Having the amount of child elements and the root, just create a loop of 0 up to the amount of child elements, with this you can access each index through the method getChild.

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 there are internally
- Start a loop from 0 to the number of elements.


How can I have access to the example path or index ?

// 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 together a simple test code containing the same JTree created by you in the question, follows the image:

jtree is nice

The example is simple: It will access the two child elements (Example1 > 1 and Example 2 > 2) and store the name in a String. The exit is:

1
2


import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

public class MyWindow extends JFrame {

    public MyWindow() {
        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);
    }
}

4


Only by complementing the @Renan response, you can also scan the JTree in that way:

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);
    }
}

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

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

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

The result can be seen in the image below.

resultado do código

Browser other questions tagged

You are not signed in. Login or sign up in order to post.