Вы должны применить 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;
}
}
}
Большое спасибо, я выложу код и более подробное объяснение проблемы! – iainmac
вот ссылка на вопрос, если у вас есть мысли, что было бы здорово! http://stackoverflow.com/questions/15489102/dynamically-changing-contents-of-listcellrenderer – iainmac
@iainmac Обычно для редактирования существующего вопроса нужно добавить пример, а не создавать новый вопрос. – rob