JavaFX 8 Image load (Invalid URL or resource not f

2019-09-01 06:30发布

问题:

as said there docs.oracle about Image class:

// 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);

I shared my simple project at github, so you can easily access code.
and this is piece of my code:

splashScreen = new Image("/gravixsplash.png");
splashScreenBackplate = new ImageView();
splashScreenBackplate.setImage(splashScreen);

instructionLayer = new Image("/gravixinstructions.png");
splashScreenTextArea = new ImageView();
splashScreenTextArea.setImage(instructionLayer);

But this don't wanna work for me, I get this:

Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found at javafx.scene.image.Image.validateUrl(Image.java:1081)

at (Image.java:1081) I find this:

if (resource == null) {
    throw new IllegalArgumentException("Invalid URL or resource not found");
}

I assume that my url(resource) is for some reason equal to null, but it didn't help me find the solution.

(Maybe somehow I need to turn on javaFX8, i suspect that intellijIDEA build javaFX2 project, I was searching for this in settings, but didn't find anything)

回答1:

The images in your project aren't in the root of your class path, they are in:

 /ru/petrsu/javafxGame/

So instead of:

new Image("/gravixsplash.png")

Use:

new Image("/ru/petrsu/javafxGame/gravixsplash.png")

From the Image javadoc:

If the passed string is not a valid URL, but a path instead, the Image is searched on the classpath in that case.