Java Swing How to - Build JTree from strings








Question

We would like to know how to build JTree from strings.

Answer

import java.util.Enumeration;
//  ww w  .ja v  a2 s .co  m
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();
  }
}