JavaFX遇到错误JavaFX Invalid URL: Invalid URL or resource not found

记录一个JavaFX老古董开发遇到的问题
依照jdk8提供的四种方法

import javafx.scene.image.Image;

// load an image in background, displaying a placeholder while it's loading
// (assuming there's an ImageView node somewhere displaying this image)
// The image is located in default package of the classpath
Image image1 = new Image("/flower.png", true);

// load an image and resize it to 100x150 without preserving its original
// aspect ratio
// The image is located in my.res package of the classpath
Image image2 = new Image("my/res/flower.png", 100, 150, false, false);

// load an image and resize it to width of 100 while preserving its
// original aspect ratio, using faster filtering method
// The image is downloaded from the supplied URL through http protocol
Image image3 = new Image("http://sample.com/res/flower.png", 100, 0, false, false);

// load an image and resize it only in one dimension, to the height of 100 and
// the original width, without preserving original aspect ratio
// The image is located in the current working directory
Image image4 = new Image("file:flower.png", 0, 100, false, false);

最后都抛出资源没找到的异常

解决方法

import javafx.scene.image.Image;
import javafx.scene.image.ImageView;


@FXML
private ImageView favicon;


@FXML
public void initialize() {
    Image image = new Image(getClass().getResource("文件路径").toExternalForm());
    favicon.setImage(image);
}

在中文文件路径下输入文件的路径,根路径为src,即/static就是src下的static文件夹

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容