简体   繁体   English

当 ImageIcon(String) 的路径无效 (Java) 时会发生什么?

[英]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?您可以使用ImageIcon icon = new ImageIcon("an image.png")创建一个新的ImageIcon ,但是如果"an image.png"不存在或发生其他错误会怎样? 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?我正在写一个程序,加载图像这样的,我想检查是否有加载图像的问题,但由于没有Exception被抛出时,你会怎么检查? Would if (icon == new ImageIcon()) be the correct statement? if (icon == new ImageIcon())是正确的说法吗?

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编辑:我使用的ImageIO.read确实会引发异常并使检查变得容易,但我需要加载的一些图像是动画 gif,如果使用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.当 ImageIcon (String) 的路径无效时会发生图像不会显示并且不会出现错误的情况。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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