The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.tree  [15 examples]

e1020. Changing and Removing the Default Icons in a JTree Component

There are three icons used by the default tree component. The open icon is used to display an open internal node that can contain children. The closed icon is used to display a closed internal node that can contain children. The leaf icon is used for nodes that cannot contain children.

These icons can be changed individually. However, it is more typical that if one needs to be changed, all three are changed together. The reason is that each look and feel installs its own set of icons, often with differing dimensions. If you change only one of the three icons, the new icon may visibly match one look and feel but it will not match the others.

There are two ways to change the icons. The first is to override the UI defaults. With this method, all new tree components will have the new icons. The second method is to update the renderer for a particular tree component. This method only affects that tree component and no other.

When overriding the icons, you should set the row height. See e1031 Setting the Row Height of a JTree Component for more information.

    // Retrieve the three icons
    Icon leafIcon = new ImageIcon("leaf.gif");
    Icon openIcon = new ImageIcon("open.gif");
    Icon closedIcon = new ImageIcon("closed.gif");
    
    // Create tree
    JTree tree = new JTree();
    
    // Update only one tree instance
    DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer)tree.getCellRenderer();
    renderer.setLeafIcon(leafIcon);
    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;
    // see e1031 Setting the Row Height of a JTree Component

 Related Examples
e1019. Creating a JTree Component

See also: Events    Layout    Node Expansion    Nodes    Selections   


© 2002 Addison-Wesley.