Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a Jlist with alternating colors

Tags:

java

swing

jlist

In Java how do I get a JList with alternating colors? Any sample code?

like image 292
Frank Avatar asked Jul 02 '09 20:07

Frank


1 Answers

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.

like image 86
jjnguy Avatar answered Oct 30 '22 16:10

jjnguy