简体   繁体   中英

What happens when a path for ImageIcon(String) is invalid (Java)?

You can create a new ImageIcon with ImageIcon icon = new ImageIcon("an image.png") , but what happens if "an image.png" doesn't exist, or some other error occurs? I'm writing a program that loads images like this, and I want to check if there was a problem loading an image, but since no Exception is thrown, how would you check that? Would if (icon == new ImageIcon()) be the correct statement?

EDIT: I was using ImageIO.read which does throw an exception and makes checking easy but some of the images I need to load are animated gifs which don't animate if you load them with ImageIO.read

What happens when a path for ImageIcon (String) is not valid is that the image will not be displayed and no errors will be appears.

You can check if the image file exists by doing this:

Path path = Paths.get("image.png");
if (Files.exists(path))
    //the image exists
else
    //the image does not exists

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM