Java Swing How to - Add children nodes from objects to JTree








Question

We would like to know how to add children nodes from objects to JTree.

Answer

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
/*from w w w  . ja va  2  s . c o  m*/
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class Main {
  public static void main(String[] args) {
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
    DefaultTreeModel model = new DefaultTreeModel(root);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new JScrollPane(new JTree(model)));
    f.getContentPane().add(
        new JButton(new AbstractAction("Add thousand children") {
          @Override
          public void actionPerformed(ActionEvent e) {
            int offset = root.getChildCount() + 1;
            for (int i = 0; i < 1000; i++) {
              DefaultMutableTreeNode child = new DefaultMutableTreeNode(
                  "Person " + (i + offset));
              // model.insertNodeInto(child, root, root.getChildCount());
              root.add(child);
            }
            model.nodeStructureChanged(root);
          }
        }), BorderLayout.PAGE_END);
    f.pack();
    f.setVisible(true);
  }
}