简体   繁体   中英

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

如何动态更改在JList中选择的项目的背景颜色?

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());
 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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM