Create JTree visitor to visit all nodes in a JTree in Java

Description

The following code shows how to create JTree visitor to visit all nodes in a JTree.

Example


//  www. ja v a2s  . c  om
import java.util.Enumeration;

import javax.swing.JTree;
import javax.swing.tree.TreeNode;

public class Main {
  public static void main(String[] argv) throws Exception {
    JTree tree = new JTree();
    visitAllNodes(tree);
  }
  public static void visitAllNodes(JTree tree) {
    TreeNode root = (TreeNode) tree.getModel().getRoot();
    visitAllNodes(root);
  }

  public static void visitAllNodes(TreeNode node) {
    System.out.println(node);
    if (node.getChildCount() >= 0) {
      for (Enumeration e = node.children(); e.hasMoreElements();) {
        TreeNode n = (TreeNode) e.nextElement();
        visitAllNodes(n);
      }
    }
  }
}




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer