如何生成交替颜色的Jlist
在Java中如何获得具有交替颜色的JList
? 任何示例代码?
要自定义JList
单元格的外观,您需要编写自己的ListCellRenderer
实现。
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; } }
要使用此渲染器,请在JList
的构造函数中输入以下代码:
setCellRenderer(new MyListCellThing());
要根据selected并具有焦点来更改单元格的行为,请使用提供的布尔值。