0

I'm trying to put the String spath into setIcon.

The path is already save as String, it looks like C:\Users\Aron\Desktop\220i.jpg

then i try setIcon by using this string path

imagelabel.setIcon(spath)

it shows that string cannot convert to icon. what i should do to fix this.

the thing is it need to use the existing path which already stored in the string. what should i do?

Braj
  • 46,415
  • 5
  • 60
  • 76
user3866927
  • 11
  • 1
  • 2

2 Answers2

1

You need to load the image first...

BufferedImage img = ImageIO.read(new File("C:/Users/Aron/Desktop/220i.jpg"));

nb: ImageIO.read throws an IOException, this is very deliberate, as it provides better management than other image loading methods

You then need to wrap it in an ImageIcon class...

ImageIcon icon = new ImageIcon(img);

You can then pass it to setIcon...

imagelabel.setIcon(icon);

Take a look at How to Use Labels and Reading/Loading an Image for more details

FYI: C:/Users/Aron/Desktop/220i.jpg is only relevant to your current context. If your move your program to another computer, this image will no longer exists. You would be better off including the image as an embedded resource within the result application jar or as an image stored relative to your application.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

I suggest you to put the images in the project itself as resources otherwise this code might not work on another system. Try to avoid absolute path.


You should use ImageIO class to load the images that throws exception if image is not found.

You can try any one based on image location.

// Read from same package 
Image image = ImageIO.read(getClass().getResourceAsStream("c.png"));

// Read from images folder parallel to src in your project
Image image = ImageIO.read(new File("images/c.jpg"));

// Read from src/images folder
Image image = ImageIO.read(getClass().getResource("/images/c.png"))

// Read from src/images folder
Image image = ImageIO.read(getClass().getResourceAsStream("/images/c.png"))

Convert Image to ImageIcon:

ImageIcon icon = new ImageIcon(image);

Read more...

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76