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

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

问题描述

我有一个需要显示图像的简单程序。
我知道如何从Eclipse运行代码,我知道如何从JAR文件运行,但我想要一个解决方案,这两种情况都可以。



Eclipse项目是这样的:

   -  Project(java)
- src
- 控制器
- Main.java
- ui
- Display.java
- 图像
- image.jpg

在Eclipse中工作的代码片段:

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

JAR(都在一个JAR文件中):

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

我需要改变才能获得在两种情况下工作的单一代码?

解决方案

images folder insid e。 src 文件夹,Eclipse将图像复制到目标文件夹( bin 类,通常),这将使它们可以从类路径,就像他们在您的应用程序的发布版本的jar中。



getResource()不在jar中。它在类加载器的类路径中。因此,图像是否在一个罐子中是不重要的。它必须在类路径中。显然,eclipse( bin classes )的目标文件夹在应用程序的运行时类路径中,当您从Eclipse启动它。


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 project is as such:

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

The code snippet that works from within Eclipse:

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

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?

解决方案

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() 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天全站免登陆