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

4

8

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

Calvin answered 16/10, 2009 at 8:37 Comment(0)
M
23

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());
Mclin answered 16/10, 2009 at 9:12 Comment(0)
M
1

An easier way would be to go to design mode in Eclipse, and in the properties of your JList, click on the button that has two small arrows with a big yellow arrow inbetween to open up "show advanced properties." then scroll down and change the color where it says "selectionBackground" and change the color there (it will probably be gray, but it will still change). Now, when you run your program, whatever you select, the background will be that color.

Month answered 30/3, 2012 at 8:12 Comment(0)
T
1
 jList1.setSelectedIndex(currentLine);
 jList1.setSelectionBackground(Color.red);

Just Set Selected index of all the items you want to color in a loop and Change the color Accordingly!

Trousseau answered 8/5, 2015 at 9:41 Comment(0)
D
0

If I am clearly understanding you, look into javax.swing.ListCellRenderer. You need to reimplement it or extend javax.swing.DefaultListCellRenderer and customize the getListCellRendererComponent method.

Discolor answered 16/10, 2009 at 8:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.