将 ListCellRenderer 应用于 JList 上的各个单元格

iai*_*mac 0 java swing jlist listcellrenderer

是否可以将 a 应用于listcellrenderera 中的一个单元格jlist?我的代码目前在应用渲染器方面工作正常,但我想为每个条目设置不同的动态变量。抱歉,如果这有点模糊。

总而言之 - 我listcellrenderer只想应用于列表中的一个单元格,我该怎么做?

rob*_*rob 5

您必须将 ListCellRenderer 应用于列表中的所有元素,但这并不意味着它必须以相同的方式渲染所有元素。例如,您可以根据单元格的值(原始值,甚至仅基于值的类,甚至基于单元格的索引)来渲染单元格:

package com.example;

import java.awt.Color;
import java.awt.Component;

import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;

public class ListCellRendererExample extends JFrame {

    public ListCellRendererExample() {
        DefaultListModel model = new DefaultListModel();
        model.addElement(Color.BLUE);
        model.addElement("hello");
        model.addElement(5);
        model.addElement(Color.RED);

        JList jlist = new JList(model);
        jlist.setCellRenderer(new SuperDuperListCellRenderer());
        add(new JScrollPane(jlist));

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setLocationByPlatform(true);
        setVisible(true);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        new ListCellRendererExample();
    }

    private static class SuperDuperListCellRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList list, Object value,
                int index, boolean isSelected, boolean cellHasFocus) {

            // If the value is a color, give the cell a blank value but save its
            // value so we can later change its background to the value's color.
            Color bgColor = null;
            if (value instanceof Color) {
                bgColor = (Color) value;
                value = " ";
            }

            // Prepend the index to the "even" rows (the first row is row 1)
            if ((index + 1) % 2 == 0) {
                value = index + ": " + value;
            }

            Component renderComponent = super.getListCellRendererComponent(
                    list, value, index, isSelected, cellHasFocus);

            // If the value is a color, set the cell's background to that color.
            if (bgColor != null) {
                renderComponent.setBackground(bgColor);
            }

            return renderComponent;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)