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

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

总结一下 – 我想将listcellrenderer只应用于列表中的一个单元格,我该怎么做?

是否可以将listcellrenderer应用于jlist中的纯单个单元格?

不,所有单元格都必须共享相同的渲染器。 这就是渲染器的工作方式。

我的代码目前在应用渲染器时工作正常,但我想为每个条目设置不同的动态变量。

这可以做到。 渲染器可以根据应该渲染的数据状态更改渲染单元格的方式。

抱歉,如果这有点模糊..

如果您解释更多并显示代码,总会更好。

总结一下 – 我想将listcellrenderer只应用于列表中的一个单元格,我该怎么做?

再次让渲染器的行为取决于单元格所持有的值。 有关更详细的答案,请考虑创建和发布sscce并解释更多(例如,渲染方式不同?)。

您必须将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; } } }