Yuri
Yuri

Reputation: 39

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.

Upvotes: 1

Views: 367

Answers (2)

XtremeBaumer
XtremeBaumer

Reputation: 6435

you will need a inputstream to read the picture. use it like this:

File f = new File("filepath");
        InputStream in=new FileInputStream(f);
            if (in != null) {
                ImageIcon imageIcon = new ImageIcon(ImageIO.read(in));
                label.setIcon(imageIcon);
            } else {
                LOG.debug("No icon found...");
            }

Upvotes: 0

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

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

Upvotes: 1

Related Questions