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

后端 未结 4 1721
暗喜
暗喜 2021-02-06 06:32

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

相关标签:
4条回答
  • 2021-02-06 07:07
     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!

    0 讨论(0)
  • 2021-02-06 07:11

    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());
    
    0 讨论(0)
  • 2021-02-06 07:17

    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.

    0 讨论(0)
  • 2021-02-06 07:19

    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.

    0 讨论(0)
提交回复
热议问题