views:

427

answers:

2

I want to set the font color for the lines/entries in a JCombobox, unique for each line. So basically when you click the dropdown arrow, you should see a few lines that are different colors, and I want to specify the colors myself based on their properties. How should I go about doing this? Thanks!

+1  A: 

You'll probably have to provide a custom renderer for your JComboBox, check out Sun's tutorial here:

http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html#renderer

(Sorry for the lack of a link, can't post links yet since I'm a new member)

thedude19
+1  A: 

You need to create a custom ListCellRenderer as such:

class Renderer extends JLabel implements ListCellRenderer {

and implement this method:

public Component getListCellRendererComponent(JList list, Object value,
   int index, boolean isSelected, boolean cellHasFocus) {
  // Get the selected index. (The index param isn't
  // always valid, so just use the value.)

  if (isSelected) {
   setBackground(list.getSelectionBackground());
   setForeground(list.getSelectionForeground());
  } else {
   setBackground(list.getBackground());
   setForeground(list.getForeground());
  }

  // Display the text
  String text = (String) value;
  setText(text);

  // Get the source

Then, depending on your source, use this.setForeground(Color color) to set the color of your text. Finally,

return this;

}

Carl