Search code examples
javaswingjtreecellrenderer

JTree TreeCellRenderer raising issue on showing the selection color


I am using this below piece of code:

 class CountryTreeCellRenderer implements TreeCellRenderer {
        private JLabel label;

        CountryTreeCellRenderer() {
            label = new JLabel();
        }

        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            Object o = ((DefaultMutableTreeNode) value).getUserObject();
            if (o instanceof Country) {
                Country country = (Country) o;
                label.setIcon(new ImageIcon(country.getFlagIcon()));
                label.setText(country.getName());
            } else {
                label.setIcon(null);
                label.setText("" + value);
            }
            return label;
        }
    }

Since I am passing/returning a label, so on selecting any component in the JTree, no selection color is coming. I tried to use:

JComponent comp = (JComponent) super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
comp.setOpaque(true);
if(selected)
comp.setBackground(Color.RED);

But if I return comp, then the output of the tree is not coming as expected.

How to resolve the same?

I did not implement any Editor for the same.


Solution

  • Please take a look at the source code of the DefaultTreeCellRenderer, which extends JLabel as well and is perfectly capable of setting a background color. I copy-pasted the relevant lines below:

      if (selected)
        {
          super.setBackground(getBackgroundSelectionColor());
          setForeground(getTextSelectionColor());
    
          if (hasFocus)
            setBorderSelectionColor(UIManager.getLookAndFeelDefaults().
                                    getColor("Tree.selectionBorderColor"));
          else
            setBorderSelectionColor(null);
        }
      else
        {
          super.setBackground(getBackgroundNonSelectionColor());
          setForeground(getTextNonSelectionColor());
          setBorderSelectionColor(null);
        }