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

后端 未结 4 1725
暗喜
暗喜 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: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());
    

提交回复
热议问题