Reputation: 7386
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);
}
Upvotes: 3
Views: 4887
Reputation: 7386
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
Upvotes: 3
Reputation: 109813
don't provide FileIO inside XxxRenderer, load all Icons to local variable, test for null value
XxxRenderer firing a lots of event (mouse, keys and internally implemented in API), then you recreated Icon on fly
read Oracle tutorial about JComboBox, try code example about similair issue
Upvotes: 1
Reputation: 16234
"/pics/Color-icon.png"
Does this exist? ImageIcon
won't throw any exceptions if it fails to load the image, but will return null
.
Upvotes: 1