您可以使用 ImageIcon icon = new ImageIcon("an image.png")
创建一个新的 ImageIcon
,但是如果 "an image.png 会发生什么"
不存在,或者发生其他错误?我正在编写一个像这样加载图像的程序,我想检查加载图像是否有问题,但由于没有抛出 Exception
,您将如何检查? if (icon == new ImageIcon())
是正确的陈述吗?
编辑:我使用的是 ImageIO.read
,它会抛出异常并使检查变得容易,但我需要加载的一些图像是动画 gif,如果你用 ImageIO.read
最佳答案
当 ImageIcon (String) 的路径无效时,将不会显示图像,也不会出现任何错误。
您可以通过执行以下操作检查图像文件是否存在:
Path path = Paths.get("image.png");
if (Files.exists(path))
//the image exists
else
//the image does not exists
关于java - 当 ImageIcon(String) 的路径无效时会发生什么 (Java)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38901893/