Java – how to generate JList with alternating colors
•
Java
How do I get an alternate color JList in Java? Any sample code?
Solution
To customize the appearance of JList cells, you need to write your own listcellrenderer implementation
An example implementation of this class might be as follows: (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, put this code in your JList constructor:
setCellRenderer(new MyListCellThing());
To change the behavior of a cell based on the selected and having focus, use the supplied Boolean value
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码