Everyone already wanted to put an image on a Combo Box, whether to show country flags, avatars or even simple icons. I'll show you how to do this in Java Swing using JComboBox.
We need to create two classes:
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
@SuppressWarnings("rawtypes")
public class LanguagesComboBox extends JComboBox {
private static final long serialVersionUID = 1L;
private ImageIcon img;
private String[][] LIST_LANGUAGES = new String[][] { { "pt", "pt.jpg" }, { "en", "en.jpg" } };
@SuppressWarnings("unchecked")
public LanguagesComboBox() {
for (String[] item : LIST_LANGUAGES) {
img = new ImageIcon(getClass().getResource("/images/flags_language/" + item[1]));
img.setDescription(item[0]);
this.addItem(img);
}
LanguageComboBoxRenderer renderer = new LanguageComboBoxRenderer();
setRenderer(renderer);
setEditable(false);
}
public void setSelectedLanguage(String value) {
for (int i = 0; i < LIST_LANGUAGES.length; i++) {
if (value.equals(LIST_LANGUAGES[i][0])) {
img = new ImageIcon(getClass().getResource("/images/flags_language/" + LIST_LANGUAGES[i][1]));
img.setDescription(LIST_LANGUAGES[i][0]);
setSelectedIndex(i);
}
}
}
}
import java.awt.Component;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
@SuppressWarnings("rawtypes")
class LanguageComboBoxRenderer extends JLabel implements ListCellRenderer {
private static final long serialVersionUID = 1L;
public LanguageComboBoxRenderer() {
setOpaque(true);
setHorizontalAlignment(LEADING);
setVerticalAlignment(CENTER);
}
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
ImageIcon icon = (ImageIcon)value;
Image img = icon.getImage().getScaledInstance(30, 22, Image.SCALE_DEFAULT);
setText(icon.getDescription());
setIcon(new ImageIcon(img));
return this;
}
}
Example of Use:
LanguagesComboBox cbLanguages = new LanguagesComboBox();
YOUR_PAINEL.add(cbLanguages);
The images used in this example need to be in this path: src/images/flags_language/
Click Here to download the images used in this example.