How to color different elements in the JComboBox

Hi,I have a combo box with say 10 items.I want to colour different items inside the combo box with differrent color.How to do this.?thnx & regardsNeel
[182 byte] By [neela] at [2007-10-2 18:27:14]
# 1
try http://java.sun.com/javase/6/docs/api/javax/swing/JComboBox.htmlI don't have an exact answer, but maybe you can find one there yourself.
Pilfera at 2007-7-13 19:48:23 > top of Java-index,Desktop,Core GUI APIs...
# 2
set your own renderer which extends DefaultListCellRendererthe trick is to set the color for every index, not just "every 2nd index"
Michael_Dunna at 2007-7-13 19:48:23 > top of Java-index,Desktop,Core GUI APIs...
# 3

hi,

Thanks.It worked with the following Rendeerer

class MyCellRenderer extends JLabel implements ListCellRenderer {

Vector indexVec=new Vector();

public MyCellRenderer() {

setOpaque(true);

}

public MyCellRenderer(Vector indexVec) {

setOpaque(true);

this.indexVec=indexVec;

}

public Component getListCellRendererComponent(JList list,

Object value,

int index,

boolean isSelected,

boolean cellHasFocus) {

setText(value.toString());

Color background=Color.WHITE;

Color foreground=Color.BLACK;

if(indexVec.contains(new Integer(index))){

foreground=Color.RED;

}else{

foreground=Color.GREEN;

}

setBackground(background);

setForeground(foreground);

return this;

}

}

but I have a problem now.previously for selection of a element or navigation from one item to the other item in the combo baox i used to get a dark blue background showing in which item I am presently now......but after adding this MyCellRenderer that is gone.

Please help in what could be the prob....how to set that color..

thnx

~Neel

neela at 2007-7-13 19:48:23 > top of Java-index,Desktop,Core GUI APIs...
# 4

the default component for combobox is a Jlabel, so you only need to

extend DefaultListCellRenderer.

this should answer your navigation question

import java.awt.*;

import javax.swing.*;

class Testing extends JFrame

{

JComboBox cbo = new JComboBox(new String[]{"London","Madrid","New York","Rome","Sydney","Washington"});

public Testing()

{

setSize(150,75);

setLocation(400,300);

setDefaultCloseOperation(EXIT_ON_CLOSE);

cbo.setRenderer(new MyRenderer());

JPanel jp = new JPanel();

jp.add(cbo);

getContentPane().add(jp);

}

public static void main(String args[]){new Testing().setVisible(true);}

}

class MyRenderer extends DefaultListCellRenderer

{

public Component getListCellRendererComponent(JList list,Object value,

int index,boolean isSelected,boolean cellHasFocus)

{

JLabel lbl = (JLabel)super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);

if(isSelected) lbl.setBackground(UIManager.getColor("ComboBox.selectionBackground"));

else if(index%2==0) lbl.setBackground(Color.PINK);

else lbl.setBackground(Color.YELLOW);

return lbl;

}

}

Michael_Dunna at 2007-7-13 19:48:23 > top of Java-index,Desktop,Core GUI APIs...