Question

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);
}
Was it helpful?

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

OTHER TIPS

"/pics/Color-icon.png"

Does this exist? ImageIcon won't throw any exceptions if it fails to load the image, but will return null.

  1. don't provide FileIO inside XxxRenderer, load all Icons to local variable, test for null value

  2. XxxRenderer firing a lots of event (mouse, keys and internally implemented in API), then you recreated Icon on fly

  3. read Oracle tutorial about JComboBox, try code example about similair issue

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