3

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

Matthew Flynn
  • 191
  • 1
  • 12
  • 1
    *".. I want to check if there was a problem loading an image"* Then use `ImageIO.read(..)`. It provides lots of helpful feedback, unlike the `ImageIcon` constructor using a `String` which will fail silently. As an aside: Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An [tag:embedded-resource] must be accessed by URL rather than file. See the [info. page for embedded resource](http://stackoverflow.com/tags/embedded-resource/info) for how to form the URL. – Andrew Thompson Aug 11 '16 at 16:39
  • @AndrewThompson Some of the images the program needs to load are animated gifs, and I was told elsewhere on stack overflow that `ImageIO.read` won't work for animated gifs, and that I had to use `ImageIcons` for that – Matthew Flynn Aug 11 '16 at 16:43
  • *"animated gifs, and I was told elsewhere on stack overflow .."* Likely here: [Show an animated BG in Swing](http://stackoverflow.com/q/10836832/418556). *"..that ImageIO.read won't work for animated gifs"* True. While the `Toolkit` has various methods that work for loading animated GIFs, they are just as uninformative as the `ImageIcon` .. – Andrew Thompson Aug 11 '16 at 16:52

1 Answers1

-1

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
Ous Mass
  • 1
  • 2