PrintDescendants.java Source code

Java tutorial

Introduction

Here is the source code for PrintDescendants.java

Source

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 PrintDescendants {
    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("Mars");
        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);

        printDescendants(root);
    }

    public static void printDescendants(TreeNode root) {
        System.out.println(root);
        Enumeration children = root.children();
        if (children != null) {
            while (children.hasMoreElements()) {
                printDescendants((TreeNode) children.nextElement());
            }
        }
    }
}