Start New Discussion within our Software Development Community

Hey

I'm building a application and using JTree to navigate between the functions. This is working but can't figure out how to set up the JTree to have different icons for each node.

I can have one default icon that gets rendered to each node or set up an icon for when it is opened or closed but can't set up individual icons.

any help would be welcomed.

You can do it with a custom cell renderer like so:

class CustomIconRenderer extends DefaultTreeCellRenderer {
    ImageIcon defaultIcon;
    ImageIcon specialIcon;

    public CustomIconRenderer() {
        defaultIcon = new ImageIcon(CustomIconRenderer.class.getResource("/images/defaultIcon.gif"));
        specialIcon = new ImageIcon(CustomIconRenderer.class.getResource("/images/specialIcon.gif"));
    }

    public Component getTreeCellRendererComponent(JTree tree,
      Object value,boolean sel,boolean expanded,boolean leaf,
      int row,boolean hasFocus) {

        super.getTreeCellRendererComponent(tree, value, sel, 
          expanded, leaf, row, hasFocus);

        Object nodeObj = ((DefaultMutableTreeNode)value).getUserObject();
        // check whatever you need to on the node user object
        if (((WhateverNodeObjectClass)nodeObj).someProperty) {
            setIcon(specialIcon);
        } else {
            setIcon(defaultIcon);
        } 
        return this;
    }
}
This question has already been answered. Start a new discussion instead.