从 JAR 或文件系统加载 ImageIcon [英] Loading ImageIcon from JAR or file system

查看:23
本文介绍了从 JAR 或文件系统加载 ImageIcon的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要显示图像的简单程序.我知道如何从 Eclipse 运行代码来执行此操作,并且我知道如何从 JAR 文件运行它,但我想要一个在这两种情况下都适用的解决方案.

I have a simple program that needs to display images. I know how to do this running the code from Eclipse and I know how to do it running from a JAR file, but I'd like a solution that works in both cases.

Eclipse 项目是这样的:

Eclipse project is as such:

- Project (java)
  - src
    - controller
      - Main.java
    - ui
      - Display.java
  - images
    - image.jpg

在 Eclipse 中工作的代码片段:

The code snippet that works from within Eclipse:

ImageIcon image = new ImageIcon("images/image.jpg);

适用于 JAR 的那个(全部在一个 JAR 文件中):

The one that works for a JAR (all in a single JAR file):

java.net.URL imgURL = getClass().getResource("/images/image.jpg");
ImageIcon image = new ImageIcon(imgURL);

我需要更改什么才能获得在这两种情况下都可以使用的一段代码?

What would I need to change in order to get a single piece of code that works in both situations?

推荐答案

images 文件夹放在 src 文件夹中,Eclipse 会将图像复制到目标文件夹中(binclasses,通常),这将使它们从类路径中可用,就像它们在应用程序的已发布版本中的 jar 中一样.

Put the images folder inside the src folder, and Eclipse will copy the images into the target folder (bin or classes, generally), which will make them available from the classpath, just as if they were in your jar in the released version of your app.

getResource() 看起来不是在 jar 中.它在类加载器的类路径中查找.因此,图像是否在 jar 中并不重要.它必须在类路径中.很明显,当您从 Eclipse 启动应用程序时,eclipse 的目标文件夹(通常为 binclasses)位于应用程序的运行时类路径中.

getResource() doesn't look in a jar. It looks in the classpath of the classloader. Whether the image is in a jar or not is thus not important. It must be in the classpath. And obviously the target folder of eclipse (bin or classes, generally) is in the runtime classpath of the app when you launch it from Eclipse.

这篇关于从 JAR 或文件系统加载 ImageIcon的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆