Java JTree Create createTreeNode(String text, int depth)

Here you can find the source of createTreeNode(String text, int depth)

Description

Creates a random tree of nodes of type MutableTreeNode (actually: DefaultMutableTreeNode).

License

Open Source License

Parameter

Parameter Description
text the text of the root
depth the depth of the tree

Return

a tree of random nodes

Declaration

public static MutableTreeNode createTreeNode(String text, int depth) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Random;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;

public class Main {
    private static Random random = new Random();

    /**/*from  www.ja  va 2 s. c  om*/
     * Creates a random tree of nodes of type MutableTreeNode 
     * (actually: DefaultMutableTreeNode). Copied from
     * test.aephyr.swing.TreeSort
     * <p>
     * 
     * PENDING JW: add option to initialize with the same random sequence.
     * 
     * @param text the text of the root
     * @param depth the depth of the tree
     * @return a tree of random nodes
     */
    public static MutableTreeNode createTreeNode(String text, int depth) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(text);
        if (--depth >= 0)
            for (int i = bellCurve(); --i >= 0;)
                node.add(createTreeNode(createCellValue(), depth));
        return node;
    }

    private static int bellCurve() {
        int i = Integer.bitCount(random.nextInt());
        if (i < 13)
            return i;
        return i - 12;
    }

    private static String createCellValue() {
        char[] c = new char[bellCurve() + 2];
        for (int i = c.length; --i >= 0;)
            c[i] = (char) (random.nextInt(26) + 'a');
        c[0] = Character.toUpperCase(c[0]);
        return new String(c);
    }
}

Related

  1. createEnumeration(String className, TreeNode root)
  2. createSimpleTreeCellRenderer(ImageIcon icon)
  3. createTree()
  4. createTree(JTree jTree1, String[] leaves)