tags:

views:

326

answers:

2

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

A: 

If I am cleary understand your - look into javax.swing.ListCellRenderer. You need or reimplement it or extend javax.swing.DefaultListCellRenderer and customize getListCellRendererComponent method.

St.Shadow
+4  A: 

Something like the following should help as a starting point:

public class SelectedListCellRenderer extends DefaultListCellRenderer {
     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());
MHarris