JTree TreeCellRenderer raising issue on showing the selection color

2.7k views Asked by At

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.

2

There are 2 answers

2
Robin On BEST ANSWER

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);
    }
0
Abhishek Choudhary On

Yes it worked as explained by Robin by bit of change basically

if(selected){
            label.setBackground(Color.YELLOW);
            label.setForeground(Color.GREEN);
        }else
             {
            label.setBackground(Color.WHITE);
            label.setForeground(Color.BLACK);
             //setBorderSelectionColor(null);
             }

enough