String array into JTree nested nodes using loop

edpanferry :

Need somebody to help. How do I put an array of strings into JTree nested nodes using loop? For example, if I have String names []={"A","B","C","D"}, the JTree result will be D child inside node C, C inside B, and B inside A. Like

  • A
    • B
      • C
        • D
Ryan :
public static <T> DefaultMutableTreeNode treeify(List<T> values) {
    DefaultMutableTreeNode root = null;
    DefaultMutableTreeNode subRoot = null;
    for (T value : values) {
        if (root == null) {
            root = new DefaultMutableTreeNode(value);
        } else if (subRoot == null){
            subRoot = new DefaultMutableTreeNode(value);
            root.add(subRoot);
        } else {
            DefaultMutableTreeNode child = new DefaultMutableTreeNode(value);
            subRoot.add(child);
            subRoot = child;
        }
    }

    return root;
}

public static void main(String [] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    JTree tree = new JTree(treeify(Arrays.asList("A", "B", "C", "D", "E")));
    frame.add(new JScrollPane(tree));
    frame.setSize(150, 300);
    frame.setVisible(true);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=183045&siteId=1