Happy new year, this is my first post in 2012, today am gonna show you step by step how to put image or ImageIcon in JComboBox. Ok, here we go, first simply create JFrame and inside of it create ImageIcon(s) and put them into array of ImageIcon, sort them as you want it to be in your JcomboBox, example :

private java.net.URL imgEnglish = getClass().getResource("english-language.gif");
private java.net.URL imgJapan = getClass().getResource("japanese-language.gif");
private ImageIcon iiEnglish = new ImageIcon(imgEnglish);
private ImageIcon iiJapan = new ImageIcon(imgJapan);
ImageIcon[] images = {iiEnglish,iiJapan};

Also create Array of String for items in JComboBox and Array of Integer for image indexing :

String[] description = {"english", "japan"};
Integer[] imageIndex = new Integer[images.length]

After that, create ComboBoxRenderer class inside of your JFrame class like this :


class ComboBoxRenderer extends JLabel implements ListCellRenderer {
public ComboBoxRenderer() {
setOpaque(true);
setHorizontalAlignment(CENTER);
setVerticalAlignment(CENTER);
}

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.)
int selectedIndex = ((Integer)value).intValue();

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

//Set the icon and text.
ImageIcon icon = images[selectedIndex];
String language = description[selectedIndex];
setIcon(icon);
if (icon != null) {
setText(language);
setFont(list.getFont());
}

return this;
}
}

Now its time to create JComboBox using ComboBoxRenderer :


for (int i = 0; i < imageIndex.length; i++) {
imageIndex[i] = i;
}

jComboBox1 = new JComboBox(imageIndex);

ComboBoxRenderer renderer= new ComboBoxRenderer();
renderer.setPreferredSize(new Dimension(200, 30));
jComboBox1.setRenderer(renderer);
jComboBox1.setMaximumRowCount(images.length);

Done, if you do it properly you gonna have JComboBox with two items, each item have image and description like picture below.

Easy isn’t? Hope the post useful, thanks for reading😉 .

For info about my newest post :