Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.Enumeration;

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class Main {
    public Main() {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("ROOT");
        DefaultTreeModel model = new DefaultTreeModel(root);
        JTree tree = new JTree(model);

        buildTreeFromString(model, "A/D/E/Node 4");
        buildTreeFromString(model, "A/C/F/Node 5");
        buildTreeFromString(model, "A/B/G/Node 6");
        buildTreeFromString(model, "A/C/H/Node 5");
        buildTreeFromString(model, "A/B/G/Node 5");

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(tree);
        f.setSize(300, 300);
        f.setLocation(200, 200);
        f.setVisible(true);
    }

    private void buildTreeFromString(final DefaultTreeModel model, final String str) {
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
        String[] strings = str.split("/");
        DefaultMutableTreeNode node = root;
        for (String s : strings) {
            int index = childIndex(node, s);
            if (index < 0) {
                DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(s);
                node.insert(newChild, node.getChildCount());
                node = newChild;
            } else {
                node = (DefaultMutableTreeNode) node.getChildAt(index);
            }
        }
    }

    private int childIndex(final DefaultMutableTreeNode node, final String childValue) {
        Enumeration<DefaultMutableTreeNode> children = node.children();
        DefaultMutableTreeNode child = null;
        int index = -1;

        while (children.hasMoreElements() && index < 0) {
            child = children.nextElement();

            if (child.getUserObject() != null && childValue.equals(child.getUserObject())) {
                index = node.getIndex(child);
            }
        }
        return index;
    }

    public static void main(String[] args) {
        new Main();
    }
}