Java Swing How to - Paint custom icon for JTree








Question

We would like to know how to paint custom icon for JTree.

Answer

import java.awt.Component;
import java.awt.Graphics;
/*from w  w  w . jav a  2 s. c  o  m*/
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.UIManager;

public class Main {

  public static void main(String[] args) {
    final JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Icon empty = new TreeIcon();
    UIManager.put("Tree.closedIcon", empty);
    UIManager.put("Tree.openIcon", empty);
    UIManager.put("Tree.collapsedIcon", empty);
    UIManager.put("Tree.expandedIcon", empty);
    UIManager.put("Tree.leafIcon", empty);

    JTree jt = new JTree();
    frame.add(jt);
    frame.pack();
    frame.setSize(300, 400);
    frame.setVisible(true);
  }
}

class TreeIcon implements Icon {

  private static int SIZE = 0;

  public TreeIcon() {
  }

  public int getIconWidth() {
    return SIZE;
  }

  public int getIconHeight() {
    return SIZE;
  }

  public void paintIcon(Component c, Graphics g, int x, int y) {
    System.out.println(c.getWidth() + " " + c.getHeight() + " " + x + " " + y);
  }
}