java 如何生成具有交替颜色的 Jlist
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1076473/
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 generate a Jlist with alternating colors
提问by Frank
In Java how do I get a JListwith alternating colors? Any sample code?
在 Java 中,如何获得JList具有交替颜色的颜色?任何示例代码?
回答by jjnguy
To customize the look of a JListcells you need to write your own implementation of a ListCellRenderer.
要自定义JList单元格的外观,您需要编写自己的ListCellRenderer.
A sample implementation of the classmay look like this: (rough sketch, not tested)
的示例实现class可能如下所示:(粗略草图,未经测试)
public class MyListCellThing extends JLabel implements ListCellRenderer {
public MyListCellThing() {
setOpaque(true);
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
// Assumes the stuff in the list has a pretty toString
setText(value.toString());
// based on the index you set the color. This produces the every other effect.
if (index % 2 == 0) setBackground(Color.RED);
else setBackground(Color.BLUE);
return this;
}
}
To use this renderer, in your JList's constructor put this code:
要使用此渲染器,请在您JList的构造函数中输入以下代码:
setCellRenderer(new MyListCellThing());
To change the behavior of the cell based on selected and has focus, use the provided boolean values.
要根据选定和具有焦点更改单元格的行为,请使用提供的布尔值。

