Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 567
Eslam Mohamed Mohamed Avatar asked Dec 04 '25 13:12

Eslam Mohamed Mohamed


2 Answers

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

like image 59
Eslam Mohamed Mohamed Avatar answered Dec 07 '25 03:12

Eslam Mohamed Mohamed


"/pics/Color-icon.png"

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

like image 20
Mordechai Avatar answered Dec 07 '25 02:12

Mordechai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!