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!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With