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

巧了我就是萌 提交于 2019-12-03 12:49:22

问题


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


回答1:


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



回答2:


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.




回答3:


 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!




回答4:


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.



来源:https://stackoverflow.com/questions/1576853/how-to-change-background-color-of-the-selected-item-in-jlist-dynamically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!