I have two strings node1/node2/node3/node4″ and “node1/node2/node5/node6″…. how can I build a ONE JTree in swing from this strings? Here is my Code that builds one string….
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.tree.*;
public class PathTest
{
public PathTest()
{
DefaultMutableTreeNode node = buildNodeFromString();
DefaultTreeModel model = new DefaultTreeModel(node);
JTree tree = new JTree(model);
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 DefaultMutableTreeNode buildNodeFromString() {
String qqq= "node1/node2/node3/node4";
DefaultMutableTreeNode node, lastNode = null, root = null;
String[] s = qqq.split("/");
for (String str : s) {
node = new DefaultMutableTreeNode(str);
if (root == null)
root = node;
if (lastNode != null)
lastNode.add(node);
lastNode = node;
}
return root;
}
public static void main(String[] args)
{
new PathTest();
}
}
Try this out, this code creates one root for the tree, and then starts to add the string under it, if you don’t want that root to show, simply call
tree.setRootVisible(false);Hope this helps.