【问题标题】:get images in eclipse, but not in .jar在eclipse中获取图像,但不在.jar中
【发布时间】:2017-05-06 07:49:07
【问题描述】:

我正在 Eclipse 中创建应用程序。当我在 Eclipse 中运行它时,它可以工作。
这是图像的路径:C:\Users\example\workspace\example\src\images
这是我的代码:

public String name;  
public Rectangle example;  
public Image exampleImage;  

public Example(String name) {
    this.name = name;
    exampleImage = new Image("./images/example.png");
    example = new Rectangle(exampleImage.getWidth(), exampleImage.getHeight());
    example.setFill(new ImagePattern(exampleImage));    
}

我从另一个文件中的此代码访问图像。

public Example example;
public void buildExample(){
    example = new Example("example");
    borderPane.getChildren().add(example.getImage());   
} 

所有的 .java 都在 src
所有图片都在图片中
在 Eclipse 中,这些目录有效:
“./images/example.png”
“文件:./src/images/example.png”
当它创建一个 .jar 文件时,路径是 Example.jar\images\
所有 .class 文件都在 Example.jar
所有图像都在图像中
当我运行 .jar 时,出现此错误:
线程“JavaFX 应用程序线程”java.lang.IllegalArgumentException 中的异常:图像必须为非空
为什么它在 Eclipse 中而不是在 .jar 中工作?

【问题讨论】:

  • 您能否显示您尝试加载图像的实际代码,而不仅仅是路径?
  • 请将jar tvf Example.jar的输出添加到问题中。
  • 输出是什么意思?

标签: java image file javafx path


【解决方案1】:

这是因为 Eclipse 只编译您的代码,它们不会将图像附加到 .jar。如果您希望它与 .jar 文件一起使用,则在 .jar 所在的文件夹中创建这些目录:“src/images/”,然后将“example.png”图像放在该目录中。运行您的 .jar,它应该会加载到图像中。

【讨论】:

  • 当我制作 .jar 文件时,我会使用 .zip 文件查看它。图片在那里
【解决方案2】:

编辑: 您发布的代码甚至无法编译!点击此链接获取如何阅读图像的教程:https://docs.oracle.com/javase/tutorial/2d/images/loadimage.html

这可能是由两件事引起的:

  1. 文件未导出到 jar 文件中。您可以通过转到 Project-Properties->Java Build Path->Source 并检查您是否包含所有文件并且不排除任何特定文件来解决此问题。
  2. 第二种可能是走错路了。不知何故,日食路径的解决方式不同。一个解决方案是通过一个类来定义路径。 假设您具有以下文件夹结构:
    Folder structure
    然后,如果您将其用作路径,则可以安全地访问图像:

    Prog.class.getResource("img/foo.jpg");

【讨论】:

  • 在 Java 构建路径中说:Example/src 下的 Included(All), Excluded(None)
  • 那么你应该选择第二种解决方案。将一个类放在上面的同一个文件夹或某个文件夹中,然后如上所述使用该类作为起点访问它
  • 顺便说一句。你通常不会加载这样的图像。例如,您可以使用 javax.imageio.ImageIO 加载图像,请查看此链接以获取详细信息:
【解决方案3】:

要从 jar 中打开文件,请使用以下方法:

URL url = this.getClass().getClassLoader().getResource(filePath);

并将url.toString() 作为构造函数参数提供给Image

【讨论】:

  • 最好使用url.toExternalForm() 而不是url.toString()
猜你喜欢
  • 1970-01-01
  • 2016-02-09
  • 2021-07-20
  • 1970-01-01
  • 2011-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-02
相关资源
最近更新 更多