In Java how do I get a JList
with alternating colors? Any sample code?
views:
1229answers:
2
+3
A:
This may help you: http://java.sun.com/developer/technicalArticles/InnerWorkings/customjlist/
Juri
2009-07-02 20:30:46
+4
A:
To customize the look of a JList
cells you need to write your own implementation of a ListCellRenderer
.
A sample implementation of the class
may look like this: (rough sketch, not tested)
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:
setCellRenderer(new MyListCellThing());
To change the behavior of the cell based on selected and has focus, use the provided boolean values.
jjnguy
2009-07-02 20:36:29
Careful, you need to handle the case where the row is selected (color changes then)
Jason S
2009-07-02 21:54:36
yeah, I mentioned that in the bottom of the post.
jjnguy
2009-07-02 22:23:46
Minor nitpick: should be setBackground rather than setBackgroundColor.
ataylor
2009-11-03 19:00:25