How can I change the background color of the item which is selected in JList dynamically?
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());
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.
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!
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.
© 2022 - 2024 — McMap. All rights reserved.