解决方法
要自定义JList单元格的外观,您需要编写自己的
ListCellRenderer
实现.
@H_404_6@该类的示例实现可能如下所示:(粗略草图,未测试)
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; } }@H_404_6@要使用这个渲染器,在你的JList的构造函数中放这个代码:
setCellRenderer(new MyListCellThing());@H_404_6@要根据所选择的并具有焦点来更改单元格的行为,请使用提供的布尔值.