How can I be sure that my javaFX application is loading images from a relative path?

醉酒当歌 提交于 2021-02-10 18:42:59

问题


I'm unable to load images in my game despite using what I thought was the proper file path in the java image class.

I've multiple file paths and extensions available, and have messed around with the file location as well, the current file structure is:

 --src

   -- main.java

   -- images

     -- the image
Image earth = new Image("file:projectName/images/img.png");

I expect it to show up once I launch my game, but it unexpectedly doesn't show up, and the game doesn't crash neither. Any help is greatly appreciated.


回答1:


First of all, images should be under the src/main/resources folder. Then you should load them as resources

new Image(this.getClass().getResource("images/img.png").toExternalForm()); or

new Image("images/img.png") - the API assumes the image is in the resource path

The path should be relative to the class you use to call getResource on.

Loading them from files will brake after assembling your application, which adds resource as part of the jar.



来源:https://stackoverflow.com/questions/57714257/how-can-i-be-sure-that-my-javafx-application-is-loading-images-from-a-relative-p

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!