I have a JComboBox and have 10 string items added in it. I want to assign different colors to each item. How i can achive this? Please help.
+1
A:
You must use a custom list cell renderer. Look into this how-to for an example.
Chandru
2010-02-09 12:58:05
can you please elaborate?
Mandar
2010-02-09 12:59:36
I've edited my reply.
Chandru
2010-02-09 13:00:19
Thanks for the reply.But is there any easier way?I tried setForeground() after each addItem() but it do not work.I don't know why.
Mandar
2010-02-09 13:05:06
Did you set the foreground within the renderer component?
Chandru
2010-02-09 13:10:55
no just on JComboBox object
Mandar
2010-02-09 13:23:19
+1
A:
You must implement a new ListCellRenderer ,which will be used by your combobox, through setRenderer, to render properly your objects.
You can extend BasicComboBoxRenderer to avoid reconding everything.
Valentin Rocher
2010-02-09 13:05:44
+2
A:
The example in Chandru's answer looks like a lot of code so I can understand why you're asking for an easier solution. However, if you subclass DefaultListCellRenderer
a lot of the work is done for you, as this renderer is a subclass of JLabel
.
JList list = ... // Create JList
// Install custom renderer.
list.setCellRenderer(new DefaultListCellRenderer() {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
// Request superclass to render the JLabel.
Component ret = super.getListCellRenderer(list, value, index, isSelected, cellHasFocus);
// Now conditionally override background if cell isn't selected.
if (!isSelected) {
String s = String.valueOf(value);
if (s.equals("Foo")) {
ret.setBackground(Color.RED);
} else {
ret.setBackground(Color.GREEN);
}
}
return ret;
}
});
Adamski
2010-02-09 13:14:40