Java Swing How to - Make unique font color for JComboBox








Question

We would like to know how to make unique font color for JComboBox.

Answer

import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.util.Hashtable;
// w w w .j  ava  2 s .c  om
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;

class Main extends JFrame {
  Hashtable<Integer, Color> table;
  JComboBox<String> c;

  public Main() {

    setLayout(new FlowLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    table = new Hashtable<Integer, Color>();
    table.put(1, Color.RED);
    table.put(2, Color.BLUE);
    table.put(3, Color.GREEN);
    table.put(4, Color.GRAY);

    c = new JComboBox<String>();
    c.addItem("Item 1");
    c.addItem("Item 2");
    c.addItem("Item 3");
    c.addItem("Item 4");
    c.addItem("Item 5");
    c.addItem("Item 6");
    c.addItem("Item 7");
    c.addItem("Item 8");

    c.setRenderer(new MyListCellRenderer(table));

    add(c);
    setSize(400, 400);
    setVisible(true);
  }

  public static void main(String args[]) {
    new Main();
  }
}

class MyListCellRenderer extends DefaultListCellRenderer {
  Hashtable<Integer, Color> table;

  public MyListCellRenderer(Hashtable<Integer, Color> table) {
    this.table = table;
    setOpaque(true);
  }

  public Component getListCellRendererComponent(JList jc, Object val, int idx,
      boolean isSelected, boolean cellHasFocus) {
    setText(val.toString());
    setForeground(table.get(idx));
    if (isSelected)
      setBackground(Color.LIGHT_GRAY);
    else
      setBackground(Color.WHITE);
    return this;
  }
}