tags:

views:

38

answers:

3

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
can you please elaborate?
Mandar
I've edited my reply.
Chandru
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
Did you set the foreground within the renderer component?
Chandru
no just on JComboBox object
Mandar
+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
+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
thanks i will try this
Mandar
You can upvote this answer (and some of the other answers) if you wish.
Adamski