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.
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;
}
});
You must use a custom list cell renderer. Look into this how-to for an example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With