How can I put different icons on various nodes in a JTree?

Jay Detwiler

A TreeCellRenderer implementation can render each object in a JTree as you like. A renderer usually customizes and returns (and reuses) a JLabel for each cell in the tree. The object to be rendered is passed in and your implementation can use whatever methods and properties of the object you need to customize the JLabel. In particular, you can design your TreeModel such that each node is an object which will implement methods to specify text and icons to use in your renderer:

public MyTreeCellRenderer implements TreeCellRenderer {	
  JLabel label;
  public MyTreeCellRenderer () {
    label = new JLabel();
    // set global properties for the label here like
    // setFont(..);
    // setBackground(..);

  public Component getTreeCellRendererComponent (JTree tree, Object value, boolean isSelected, 
					         boolean isExpanded, boolean isLeaf, int index, 
					         boolean hasFocus) {
    if (value instanceof MyData) {
    } else {
    return label;

(Assuming you've defined class MyData as the type of data in the tree.)

This is particularly extensible since each node in the tree is responsible for its own display characteristics.