在 Eclipse 中从 jar 和外部加载图像 [英] Load image from jar and outside it in eclipse

查看:21
本文介绍了在 Eclipse 中从 jar 和外部加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 eclipse 的 java 项目中有这样的结构:

I have a structure like this in my java project in eclipse:

  • src/com/myprogram/.../foo.java
  • res/icon.png
  • .project
  • ...

我知道你可以用

ImageIO.read(getClass().getResource("/res/icon.png"));

当您尝试使用 Eclipse 直接运行应用程序时出现问题,因为(我猜)res 文件夹不在 src 文件夹中,您会得到一个 null URL.我想为源代码和资源设置单独的文件夹.

The problem come when you try to run the application with eclipse directly as (I guess) res folder isn't inside src folder, you get a null URL. And I want to have separate folders for source code and for resources.

另外,我发现我可以将 res 文件夹添加到 eclipse 中的类路径,以便我可以加载它:

Also, what I have found is that I can add res folder to class-path in eclipse so I can load it with:

URL url = getClass().getResource("/res/icon.png");
if (url == null)
    url = getClass().getResource("/icon.png");
ImageIO.read(url);

但是这个添加只在你开发时需要的代码,我不喜欢做这样的事情(代码应该尽可能干净和最终).

But this add code that is only needed when you develop, and I don't like do things like this (code should be as clean and final as possible).

可以用相同的代码用两种方法读取图标吗?

Can something done so the icon is read with both methods with the same code?

推荐答案

在你的项目中创建一个resources文件夹,在eclipse中将其标记为源文件夹,把res resources 下的文件夹,并确保您的非 Eclipse 构建 uts jar 中 resources 下的所有内容.然后使用

Create a resources folder in your project, mark it as a source folder in eclipse, put the res folder under resources, and make sure your non-eclipse build uts everything that is under resources in the jar. Then load the icon using

getClass().getResource("/res/icon.png")

您的问题是由于您的非 eclipse 构建将 res 放在 jar 中,但是 eclipse 将 rescontent在目标目录中.

Your problem is caused by the fact that you non-eclipse build puts res in the jar, but eclipse puts the content of res in the target directory.

这篇关于在 Eclipse 中从 jar 和外部加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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