Define a relative path of image in Java FX

自闭症网瘾萝莉.ら 提交于 2019-12-19 19:55:14

问题


I know this has been asked many times and I have searched far and wide for a solution to this probably simple problem. I'm trying to follow the simple javaFX component tutorials on Oracle's website. I can define an image this way:

Image img = new Image("images/portal.png", 50, 50, true, true);

This works when the image is in a folder inside the "src" folder, but I'm trying to get it to find the image when I have the image folder outside of the "src" folder, like this:

http://puu.sh/drF7K/bbf1a047aa.png

How can I make this work? All I get is errors saying "Invalid URL or resource not found". I've tried to use the absolute path, tried putting ".." infront of it, tried "HS-Graph/images/portal.png" and everything inbetween :( Thank you!


回答1:


I'm going to answer my own question as I actually found a solution to this! My solution is to use the "file:" prefix when specifying a path. So:

Image img = new Image("file:images/portal.png");

Works perfectly when the image file is outside of my src folder!




回答2:


I think you are running into issues because the Images folder is outside of the scope of your project. You could consider changing the structure of your project.

Ex:

->src
|-->main
    |--->java
          |-->(default package)
    |--->resources
          |-->images

Then you should be able to access your image with the path ./src/main/resources/images/portal.png




回答3:


Let me try to put it in this way; If you want to use the image found in the different directory it is better to specify its relative path. Example if i was looking for the portal image on my ImageFile. I'll do as follows:

Image img = new Image("file:images/portal.png");


来源:https://stackoverflow.com/questions/27446360/define-a-relative-path-of-image-in-java-fx

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