How to change background color of the selected item in JList dynamically

Diablo.Wu picture Diablo.Wu · Oct 16, 2009 · Viewed 16.3k times · Source

How can I change the background color of the item which is selected in JList dynamically?

Answer

MHarris picture MHarris · Oct 16, 2009

Something like the following should help as a starting point:

public class SelectedListCellRenderer extends DefaultListCellRenderer {
     @Override
     public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
         Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
         if (isSelected) {
             c.setBackground(Color.RED);
         }
         return c;
     }
}
// During the JList initialisation...
jlist1.setCellRenderer(new SelectedListCellRenderer());