Javafx:jpeg 文件存在,但图像构造函数抛出 IllegalArgumentException!为什么?

Javafx: jpeg file exists but the Image constructor throws IllegalArgumentException !Why?

为什么下面的代码会抛出这个异常?

java.lang.IllegalArgumentException: 无效 URL 或未找到资源

代码如下:

File ff=new File("images/a.jpg");
if (ff.exists()) {Image ii=new Image(ff.getPath());}

来自Javadocs

All URLs supported by URL can be passed to the constructor. If the passed string is not a valid URL, but a path instead, the Image is searched on the classpath in that case.

您获得的路径是相对路径,但不是(必然)相对于类路径的路径,这就是 Image 构造函数解释它的方式。

尝试

Image ii=new Image(ff.toURI().toURL().toExternalForm());

或者,取决于您如何设置项目结构

Image ii=new Image(getClass().getResource("images/a.jpg").toExternalForm());

如果图像文件与应用程序一起打包在 jar 文件中,则第二个版本可以使用。