Search code examples
javaswingnodesjtree

String array into JTree nested nodes using loop


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

Solution

  • 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);
    }