【记录】JavaFX导入图片无法找到的一个解决方法

703 阅读1分钟

记录一个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文件夹