Question

this is an example of what I wrote so far:

import javax.swing.*;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class program {

    JFrame win = new JFrame("bla bla");

    final private String[] animals = { "dog", "cat", "mouse" };

    private void Start() {
        JPanel superior = new JPanel();
        superior.setLayout(new GridLayout(3, 3));
        win.getContentPane().add(superior, BorderLayout.PAGE_START);
        final JComboBox<String> comboBox = new JComboBox<String>(animals);
        ((JLabel) comboBox.getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
        superior.add(comboBox);
        win.setSize(440, 290);
        win.setResizable(false);
        win.setLocationRelativeTo(null);
        win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        win.setVisible(true);
    }

    public static void main(String args[]) {
        program window = new program();
        window.Start();
    }
}

I've a single jpg for each item of animals String array in a folder called jpg placed on the same level of (default package). I'm using eclipse.

My idea was to make a JComboBox able to display only jpgs, while using strings with certain mouse click events I've already coded (but not reported just to make it short).

I've read this, this and this, but I can't really get the job done :(

Could anyone explain me how to get what I want, maybe modifying my code so I can study it?

Was it helpful?

Solution

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;
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top