我一直在尝试为JList上的项目重新着色,经过研究和尝试,我知道了!
这确实将整个行重新着色为所传递的颜色。
这是代码:
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class Main extends JFrame {
public Main() {
getContentPane().setLayout(new FlowLayout());
final JList list = new JList(new Colorable[] { new ColoredItem("Item 1", Color.yellow),
new ColoredItem("Item 2"), new ColoredItem("Item 3", Color.blue), new ColoredItem("Item 4", Color.red),
new ColoredItem("Item 5", Color.green) });
list.setCellRenderer(new ColoredCellRenderer());
getContentPane().add(new JScrollPane(list));
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
});
setSize(200, 300);
}
public static void main(String[] args) {
(new Main()).show();
}
}
class ColoredCellRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
setText((value == null) ? "" : value.toString());
System.out.println(value.toString());
Color c = ((Colorable) value).getColor();
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(c);
} else {
setBackground(list.getBackground());
setForeground(c);
}
setEnabled(list.isEnabled());
setFont(list.getFont());
return this;
}
}
class ColoredItem implements Colorable {
Object object;
Color color;
public ColoredItem(Object object, Color color) {
this.object = object;
this.color = color;
}
ColoredItem(Object object) {
this(object, Color.black);
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public String toString() {
return object.toString();
}
}
interface Colorable {
public Color getColor();
public void setColor(Color c);
}
但是这不是我想要的样子,我只想从要渲染的文本中选择一个特定的部分,在这里用数字来表示。我该如何实现呢?