How to generate a Jlist with alternating colors

隐身守侯 提交于 2019-11-30 09:02:32

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!