Search code examples
javaswingjtree

Set Imageicon for JTree node


I created a JTree. I need to change icon for specific node. Able to setIcon for closed and open as well as leafnodes but I need to set icon for specified node in my JTree. Please shed some light on this.


Solution

  • If you know how to change the default Icon, you know this happens in the TreeCellRenderer. You can simply implement a TreeCellRenderer of your own that has more advanced determining of the icon than the DefaultTreeCellRenderer.

    Something like this :

    public class MyTreeCellRenderer implements TreeCellRenderer {
    
        private final DefaultTreeCellRenderer defaultRenderer = new DefaultTreeCellRenderer();
        private final  Icon specialIcon;
    
        public MyTreeCellRenderer(Icon specialIcon) {
            this.specialIcon = specialIcon;
        }
    
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            defaultRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
            if (needsSpecialIcon(tree, value, selected, expanded, leaf, row, hasFocus)) {
                defaultRenderer.setIcon(specialIcon);
            }
            return defaultRenderer;
        }
    
        private boolean needsSpecialIcon(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            // check condition for special icon here
            return false;
        }
    }
    

    This basically delegates default behavior to DefaultTreeCellRenderer, but overrides the Icon if your special condition is true.