java 如何动态更改JList中所选项目的背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1576853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change background color of the selected item in JList dynamically
提问by Diablo.Wu
How can I change the background color of the item which is selected in JList dynamically?
如何动态更改在 JList 中选择的项目的背景颜色?
回答by MHarris
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());
回答by SpicyWeenie
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.
更简单的方法是在 Eclipse 中进入设计模式,然后在 JList 的属性中,单击带有两个小箭头和中间有一个黄色大箭头的按钮以打开“显示高级属性”。然后向下滚动并更改显示“selectionBackground”的颜色并更改那里的颜色(它可能是灰色的,但它仍然会改变)。现在,当您运行程序时,无论您选择什么,背景都将是该颜色。
回答by Bhupender Singh
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!
只需设置要在循环中着色的所有项目的选定索引并相应地更改颜色!
回答by St.Shadow
If I am clearly understanding you, look into javax.swing.ListCellRenderer.
You need to reimplement it or extend javax.swing.DefaultListCellRendererand customize the getListCellRendererComponentmethod.
如果我清楚地了解您,请查看javax.swing.ListCellRenderer. 您需要重新实现它或扩展javax.swing.DefaultListCellRenderer和自定义该getListCellRendererComponent方法。

