Search code examples
javaswingiconsjcomboboxlistcellrenderer

JComboBox with text and ImageIcon


Good morning, please,could you mind helping me in determining why this ListCellRenderer class not setting the image icon at combobox cells: here's the ListCellRenderer class:

    class MyComboRendere implements ListCellRenderer {

    public Component getListCellRendererComponent(JList list, Object value,
            int index, boolean isSelected, boolean cellHasFocus) {

        JLabel label = new JLabel();
        label.setOpaque(true);
        label.setText(value.toString());
        label.setIcon(new ImageIcon("/pics/Color-icon.png"));
        if (isSelected)
            if (index == 0)
                label.setBackground(Color.RED);
            else if (index == 1)
                label.setBackground(Color.GREEN);
            else
                label.setBackground(Color.BLUE);
        return label;
    }

}

and this is a method to setup the combobox:

public void setComboColor(){
    Vector<String> colors=new Vector<>();
    comboPanel=new JPanel(new BorderLayout());
    colors.add("RED");
    colors.add("GREEN");
    colors.add("BLUE");
    colorCombo=new JComboBox(colors);
    colorCombo.setRenderer(new MyComboRendere());
    comboPanel.add(colorCombo,BorderLayout.BEFORE_FIRST_LINE);
}

Solution

  • It seems that label.setIcon(new ImageIcon("/pics/Color-icon.png")); doesn't get the actual path of the icon as it always returns null, but it doesn't throw an exception. So I tried to use this:

    java.net.URL imgURL = getClass().getResource("/pics/Color-icon.png");
    label.setIcon(icon);
    

    and it works properly