11

在Java中,我如何获得JList交替颜色?任何示例代码?

4

1 回答 1

15

要自定义JList单元格的外观,您需要编写自己的ListCellRenderer.

的示例实现class可能如下所示:(粗略的草图,未经测试)

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;
    }
}

要使用此渲染器,请在您JList的构造函数中输入以下代码:

setCellRenderer(new MyListCellThing());

要基于选定和具有焦点更改单元格的行为,请使用提供的布尔值。

于 2009-07-02T20:36:29.443 回答