In Java how do I get a JList
with alternating colors? Any sample code?
How to generate a Jlist with alternating colors
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.
Careful, you need to handle the case where the row is selected (color changes then) –
Oceangoing
yeah, I mentioned that in the bottom of the post. –
Doublecross
Minor nitpick: should be setBackground rather than setBackgroundColor. –
Carrico
I would strongly recommend you extend
DefaultListCellRenderer
rather than implementing the interface directly. See #3270523. –
Duarte @DuncanJones do you know what you gain by doing that? –
Doublecross
I've found that it avoids the issue of having to hand-code the correct behavior when the item is selected. The default class will automatically do what's correct for the current look and feel. –
Duarte
+1 for the setCellRenderer() tip. I was extending JList and trying to use my new class instead of JList<String>. All I needed to do was set the renderer to a custom one. Thanks. –
Alikee
While extending
DefaultListCellRenderer
has the benefit of dealing with reasonable UI defaults, it should be noted that DefaultListCellRenderer
is not generic / type safe. One has to chose, either UI defaults, or generics. –
Geraldo © 2022 - 2024 — McMap. All rights reserved.