Changing the icons of a JTree

Just use the methods setOpenIcon, setClosedIcon and setLeafIcon defined in the DefaultCellRenderer class.

Here’s an example.

Main.java:

import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
 
public class Main extends JFrame
{
   public Main() {
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
      DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
      root.add(child1);
      DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");
      root.add(child2);
      JTree tree = new JTree(root);
 
      DefaultTreeCellRenderer cr = new DefaultTreeCellRenderer();
      cr.setOpenIcon(new ImageIcon("openicon.jpg"));
      cr.setClosedIcon(new ImageIcon("closedicon.jpg"));
      cr.setLeafIcon(new ImageIcon("leaficon.jpg"));
  
      tree.setCellRenderer(cr);
 
      getContentPane().add(new JScrollPane(tree));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

The icons used in this program: