Yuri Yuri - 14 days ago 5
Java Question

Error when I try to put an ImageIcon in Java

I tried to put a simple icon in a JPanel formatted with the BoxLayout.

JPanel panel_4 = new JPanel();
contentPane.add(panel_4, BorderLayout.CENTER);
panel_4.setLayout(new BoxLayout(panel_4, BoxLayout.X_AXIS));

ImageIcon seven= new ImageIcon("‪C:\\Users\\alewe\\workspace\\SlotMachine\\Lucky_Seven-128.png");

JLabel lblNewLabel_1 = new JLabel(seven);
panel_4.add(lblNewLabel_1);


When I ran the code it gave me the error "
Some characters cannot be mapped using "Cp1252" character encoding
", I saved by
UTF-8
, now it starts but I can't see the icon.

Answer

Maybe if you use setIcon will help you:

ImageIcon seven= new ImageIcon("‪C:\\Users\\alewe\\workspace\\SlotMachine\\Lucky_Seven-128.png");
JLabel lblNewLabel_1 = new JLabel();
//Set your icon to your label
lblNewLabel_1.setIcon(seven);
panel_4.add(lblNewLabel_1);

You can read more about icons here