You'll need to supply a custom ListCellRenderer
to the combobox which is capable of displaying an image (and other information as you need)
See Providing a custom renderer for more details
You can load a image using the ImageIO
API. You may need to wrap the result in a ImageIcon
in order to render it more easily, but that will depend on you API implementation
I would recommend using a DefaultListCellRenderer
as it extends from JLabel
and will make you life easier
Really simple example
I don't have enough information to form a fully runnable example, but essentially, the values added to the combo box model should, in some way, contain a reference to the image you want to load.
This way, when required, you can extract the image and display it using the cell renderer...
public class ImageCellRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof ??) {
ImageIcon icon = ...;
setIcon(icon);
}
return this;
}
}
And apply the renderer...
JComboBox cb = new JComboBox();
cb.setRenderer(new ImageCellRenderer());
Updated
Now assuming that the images are named [animal].jpg
(so dog
would be dog.jpg
) you should be able to build a simple Map
, mapping the name to the animal image...
// List of animals...
final private String[] animals = { "dog", "cat", "mouse" };
/*...*/
// Map of animal icons...
Map<String, Icon> mapImages = new HashMap<>();
// Build the icon image mapping
for (String animal : animals) {
mapImages.put(animal, new ImageIcon(ImageIO.read(getClass().getResource("/" + animal + ".jpg))))
}
// Create a new cell renderer, passing the mappings
ImageCellRenderer renderer = new ImageCellRenderer(mapImages);
// Create a new combo box
JComboBox<String> comboBox = new JComboBox<String>(animals);
// Apply the renderer
comboBox.setRenderer(renderer);
/*...*/
public class ImageCellRenderer extends DefaultListCellRenderer {
// Icon mappings
private Map<String, Icon> mapImages
public ImageCellRenderer(Map<String, Icon> mapImages) {
// Make a new reference to the icon mappings
this.mapImages = new HashMap<>(mapImages);
setHorizontalAlignment(SwingConstants.CENTER);
}
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof String) {
// Look up the icon associated with the animal...
Icon icon = mapImages.get(value.toString());
setIcon(icon);
}
return this;
}
}