在 Java FX 中定义图像的相对路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27446360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:49:13  来源:igfitidea点击:

Define a relative path of image in Java FX

javaimagepathjavafx

提问by Zorobay

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:

我知道这已经被问过很多次了,我已经广泛搜索了这个可能很简单的问题的解决方案。我正在尝试遵循 Oracle 网站上的简单 javaFX 组件教程。我可以这样定义图像:

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:

当图像位于“src”文件夹内的文件夹中时,这有效,但是当我在“src”文件夹之外拥有图像文件夹时,我试图让它找到图像,如下所示:

project_root/
 |---src/
      |---Main.java
 |---images/
      |---portal.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!

我怎样才能使这项工作?我得到的只是说“无效的 URL 或找不到资源”的错误。我尝试使用绝对路径,尝试将“..”放在它前面,尝试使用“HS-Graph/images/portal.png”以及介于两者之间的所有内容:(谢谢!

回答by Zorobay

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:

我将回答我自己的问题,因为我实际上找到了解决方案!我的解决方案是在指定路径时使用“file:”前缀。所以:

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

Works perfectly when the image file is outside of my srcfolder!

当图像文件在我的src文件夹之外时完美运行!

回答by EricF

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.

我认为您遇到了问题,因为 Images 文件夹超出了您的项目范围。您可以考虑更改项目的结构。

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

然后您应该能够使用路径 ./src/main/resources/images/portal.png 访问您的图像

回答by eli

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:

让我试着这样说;如果要使用在不同目录中找到的图像,最好指定其相对路径。例如,如果我在我的 ImageFile 上寻找门户图像。我会这样做:

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