Custom ListCellRenderer will not change background color

Grammin picture Grammin · Oct 24, 2011 · Viewed 7.4k times · Source

I have this class:

 @SuppressWarnings("serial")
  private class DataCellRenderer extends JLabel implements ListCellRenderer 
  {
    public DataCellRenderer()
    {
      setHorizontalAlignment(SwingConstants.RIGHT); 
    }

    @Override
    public Component getListCellRendererComponent(
        JList list,
        Object value,
        int index,
        boolean isSelected,
        boolean cellHasFocus)
    {

      if(isSelected)
        setBackground(Color.red);

      setText("  " + value.toString());

      return this;
    }
  }

The problem is that my Background will not turn red when I select a cell in my JList. The setText part works but I can't figure out why it will not change my background color of the cell. Anyone have any ideas, Thanks!

Answer

camickr picture camickr · Oct 24, 2011

The main problem is that labels are non-opaque by default, so you need to make the label opaque in order for the background to be painted.

But you don't need to create a custom renderer for this. The default renderer is opaque. All you need to do is set the selection background property of the list:

list.setSelectionBackground(Color.RED);

If you are trying to create a renderer to right align the text then you can just set a property on the default renderer:

DefaultListCellRenderer renderer = (DefaultListCellRenderer)list.getCellRenderer();
renderer.setHorizontalAlignment(SwingConstants.RIGHT);