how-to

Window (swing) applications

How to add items into JTree ?

This example shows how add items into javax.swing.JTree.

/* add root element */

DefaultMutableTreeNode root = new DefaultMutableTreeNode( "Root item" );
    
/* add subitems */
    
String[] names = new String[] { "Item 1", "Item 2", "Item 3" };
for ( String name : names ) {
  DefaultMutableTreeNode node = new DefaultMutableTreeNode( name );
      
  root.add(node);
}

/* set new root to the model */

jTree1.setModel( new DefaultTreeModel( root ) );