【问题标题】:How to generate a Jlist with alternating colors如何生成具有交替颜色的 Jlist
【发布时间】:2010-11-07 18:27:00
【问题描述】:

在 Java 中,我如何获得具有交替颜色的 JList?有示例代码吗?

【问题讨论】:

    标签: java swing jlist


    【解决方案1】:

    要自定义 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());
    

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

    【讨论】:

    • 小心,你需要处理选中行的情况(然后颜色改变)
    • 是的,我在帖子底部提到过。
    • 次要 nitpick:应该是 setBackground 而不是 setBackgroundColor。
    • 我强烈建议你扩展DefaultListCellRenderer 而不是直接实现接口。见stackoverflow.com/questions/3270023/…
    • 我发现它避免了在选择项目时必须手动编码正确行为的问题。默认类将自动执行适合当前外观的操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 2021-06-22
    相关资源
    最近更新 更多