微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 如何用交替颜色生成Jlist

Java中我如何获得一个交替颜色的JList?任何示例代码

解决方法

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

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

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());

要根据所选择的并具有焦点来更改单元格的行为,请使用提供的布尔值.

原文地址:https://www.jb51.cc/java/124504.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐