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