Java Swing How to - Create custom JComboBox Renderer








Question

We would like to know how to create custom JComboBox Renderer.

Answer

import java.awt.BorderLayout;
import java.awt.Component;
import java.util.Vector;
/*from ww  w .  j  a  va  2  s. c  o  m*/
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.plaf.basic.BasicComboBoxRenderer;

public class Main extends JFrame {
  public Main() {
    Vector model = new Vector();
    model.addElement(new Item(new ImageIcon("copy16.gif"), "copy"));
    model.addElement(new Item(new ImageIcon("add16.gif"), "add"));
    model.addElement(new Item(new ImageIcon("about16.gif"), "about"));

    JComboBox comboBox;

    comboBox = new JComboBox(model);
    comboBox.setRenderer(new ItemRenderer());
    getContentPane().add(comboBox, BorderLayout.SOUTH);
  }
  public static void main(String[] args) {
    JFrame frame = new Main();
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}
class ItemRenderer extends BasicComboBoxRenderer {
  public Component getListCellRendererComponent(JList list, Object value,
      int index, boolean isSelected, boolean cellHasFocus) {
    super.getListCellRendererComponent(list, value, index, isSelected,
        cellHasFocus);

    Item item = (Item) value;

    if (index == -1) {
      setText(item.getText());
      setIcon(null);
    } else {
      setText(item.getText());
      setIcon(item.getIcon());
    }
    return this;
  }
}
class Item {
  private Icon icon;
  private String text;

  public Item(Icon icon, String text) {
    this.icon = icon;
    this.text = text;
  }

  public Icon getIcon() {
    return icon;
  }

  public String getText() {
    return text;
  }
}