如何使用eclipse将图像添加到java项目中? [英] How do I go about adding an image into a java project with eclipse?

查看:158
本文介绍了如何使用eclipse将图像添加到java项目中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做了很多关于SO和Google链接的阅读。



我还没有弄清楚如何正确地将图像添加到eclipse gui项目中这样的方式,系统会认出来找到它。我知道有一些关于CLASSPATH的mumbojumbo,但它可能不应该是很难做的。



让我开始描述我在做什么...(如果有人可以纠正我,不胜感激。)



这是我的方法。



我使用导入向导(右键单击导入,常规,文件)将图像添加到导入目录中,我称之为 / resources



Eclipse在eclipse软件包资源管理器的树视图中自动创建一个名为资源的文件夹。在参考图书馆的条目下面。



注意,资源不在参考库下,它与树中的级别相同。 p>

然后我使用以下代码:

  ClassLoader classLoader = Thread.currentThread ().getContextClassLoader(); 
InputStream input = classLoader.getResourceAsStream(/ resources / image.jpg);
图片logo = ImageIO.read(input);

此时,我运行测试程序并收到此错误:

 线程main中的异常java.lang.IllegalArgumentException:input == null! 
at javax.imageio.ImageIO.read(Unknown Source)
在Test.main(Test.java:17)

感谢任何帮助提前!

解决方案

将图像放在源文件夹,而不是常规文件夹。也就是:右键单击项目 - >新建 - >源文件夹。将图像放在该源文件夹中。然后:

  InputStream input = classLoader.getResourceAsStream(image.jpg); 

请注意,路径被省略。这是因为图像直接位于路径的根部。您可以在源文件夹下添加文件夹,如果您喜欢则将其进一步分解。或者您可以将图像放在现有的源文件夹下(通常称为 src )。


I've done a lot of reading around SO and Google links.

I have yet to figure out how to correctly add an image into an eclipse gui project is such a way that the system will recognize find it. I know there's some mumbojumbo about CLASSPATH but it probably shouldn't be this difficult to do.

Let me start by describing what I'm doing...(If someone could correct me, it'd be appreciated.)

Here is my method.

I add the image using the "import wizard" (right click, "import", "general", "file") into an "import directory" I called "/resources"

Eclipse automatically creates a folder called "resources" in the eclipse package explorer's tree view. Right under the entry for "Referenced Libraries".

Note, "resources" isn't under "Referenced Libraries", it's at the same level in the tree.

I then use the following code:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("/resources/image.jpg");
Image logo = ImageIO.read(input);

And at this point, I run the test program and get this error:

Exception in thread "main" java.lang.IllegalArgumentException: input == null!
    at javax.imageio.ImageIO.read(Unknown Source)
    at Test.main(Test.java:17)

Thanks for any help in advance!

解决方案

Place the image in a source folder, not a regular folder. That is: right-click on project -> New -> Source Folder. Place the image in that source folder. Then:

InputStream input = classLoader.getResourceAsStream("image.jpg");

Note that the path is omitted. That's because the image is directly in the root of the path. You can add folders under your source folder to break it down further if you like. Or you can put the image under your existing source folder (usually called src).

这篇关于如何使用eclipse将图像添加到java项目中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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