Travel to all the nodes in a JTree with Post Order Enumeration in Java
Description
The following code shows how to travel to all the nodes in a JTree with Post Order Enumeration.
depthFirstEnumeration() and postOrderEnumeration(): Return an Enumeration that has practically the opposite behavior of preOrderEnumeration().
Instead of including the current node first and then adding the children, these methods add the children first and then add the current node to the Enumeration.
Example
//from w w w .ja v a2s .c o m
import java.awt.BorderLayout;
import java.util.Enumeration;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
public class Main {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode mercury = new DefaultMutableTreeNode("Mercury");
root.add(mercury);
DefaultMutableTreeNode venus = new DefaultMutableTreeNode("Venus");
root.add(venus);
DefaultMutableTreeNode mars = new DefaultMutableTreeNode("java2s.com");
root.add(mars);
JTree tree = new JTree(root);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
Enumeration e = root.postorderEnumeration();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »