简体   繁体   English

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

[英]Define a relative path of image in Java FX

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.我正在尝试遵循 Oracle 网站上的简单 javaFX 组件教程。 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:当图像位于“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".我得到的只是说“无效的 URL 或资源未找到”的错误。 I've tried to use the absolute path, tried putting ".." infront of it, tried "HS-Graph/images/portal.png" and everything inbetween :( Thank you!我尝试使用绝对路径,尝试将“..”放在它前面,尝试使用“HS-Graph/images/portal.png”以及介于两者之间的所有内容:(谢谢!

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.我的解决方案是在指定路径时使用“file:”前缀。 So:所以:

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

Works perfectly when the image file is outside of my src folder!当图像文件在我的src文件夹之外时完美运行!

I think you are running into issues because the Images folder is outside of the scope of your project.我认为您遇到了问题,因为 Images 文件夹超出了您的项目范围。 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然后您应该能够使用路径 ./src/main/resources/images/portal.png 访问您的图像

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.例如,如果我在我的 ImageFile 上寻找门户图像。 I'll do as follows:我会这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM