Changing and Removing the Default Icons in a JTree Component - Java Swing

Java examples for Swing:JTree

Description

Changing and Removing the Default Icons in a JTree Component

Demo Code


import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.tree.DefaultTreeCellRenderer;

public class Main {
  public static void main(String[] argv) {
    // Retrieve the three icons
    Icon leafIcon = new ImageIcon("leaf.gif");
    Icon openIcon = new ImageIcon("open.gif");
    Icon closedIcon = new ImageIcon("closed.gif");

    JTree tree = new JTree();

    // Update only one tree instance
    DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
    renderer.setLeafIcon(leafIcon);/*from ww w.ja v a  2 s.  c o m*/
    renderer.setClosedIcon(closedIcon);
    renderer.setOpenIcon(openIcon);

    // Remove the icons
    renderer.setLeafIcon(null);
    renderer.setClosedIcon(null);
    renderer.setOpenIcon(null);

    // Change defaults so that all new tree components will have new icons
    UIManager.put("Tree.leafIcon", leafIcon);
    UIManager.put("Tree.openIcon", openIcon);
    UIManager.put("Tree.closedIcon", closedIcon);

    // Create tree with new icons
    tree = new JTree();

    // Update row height based on new icons;
  }
}

Related Tutorials