如何在Eclipse上导出jar图像? [英] How to export jar with images on Eclipse?

查看:132
本文介绍了如何在Eclipse上导出jar图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一种象棋游戏(它不是棋,但我不知道如何用英文调用),我想将其导出为可运行的jar。



问题是图像(在这个程序 - 玩家)不是出于某些奇怪的原因导出。



如何使用图像在eclipse上导出runnable jar?谢谢。

解决方案

推荐的方法是拥有一个资源目录在您的项目根目录下,并将其包含在源代码目录列表中。这将导致所有图像被复制到JAR中。如果你在那里创建一个子目录 resource / image ,那么你最终会有一个JAR,它有一个图像目录。您可以通过类加载器访问这些图像:

  classloader.getResourceAsStream(/ image / name.jpg); 

或者,当您将图像传递给接受资源网址的API时:

  classloader.getResource(/ image / name.jpg); 

当然,这一切都受制于您的JAR的完整程度,但如果您通过Eclipse的Export JAR,您将能够实现我所描述的内容。如果你使用Maven,那么我有一个非常类似的方法。



还要注意,我有意避免演示代码, Java中的微不足道的题目,应以具体的上下文方式进行。但是,如果您从与图像相同的JAR中的类执行此操作,则可以通过实例方法来实现此操作:

  this.getClass()getClassLoader(); 

这个在这里是可选的,实际上不是从代码风格的角度来推荐,但是为了清楚起见,我将其包含起来,因为在你自己的任何类的实例上调用 getClass 是错误和危险的。 / p>

I created sort of chess game (it isn't exactly chess but I don't know how it called in English) and I want to export it as runnable jar.

The problem is that images (at this program - the players) are not exported for some strange reason.

How to export runnable jar on eclipse with images? thanks.

解决方案

The recommended way would be to have a resource directory under your project root and include it into the list of source code directories. This will result in all images there being copied into the JAR. If you make a subdirectory there, resource/image, then you'll end up with a JAR that has an image directory. You access those images through the classloader:

classloader.getResourceAsStream("/image/name.jpg");

or, whenever you pass the image to an API that accepts resource URLs:

classloader.getResource("/image/name.jpg");

Of course, this is all subject to how exactly you build your JAR, but if you do it through Eclipse's Export JAR, you'll be able to achieve what I'm describing. If you use Maven, there is a quite similar approach to the one I described.

Note also that I deliberately avoid demonstrating code that fetches the classloader as this is a non-trivial subject in Java and should be done in a context-specific way. However, if you do it from a class that is in the same JAR as the images, it is a safe bet that this will work from an instance method:

this.getClass().getClassLoader();

this is optional here, and is actually not recommended from the code style perspective, but I included it for clarity and because it would be wrong and dangerous to call getClass on an instance of any class other than your own.

这篇关于如何在Eclipse上导出jar图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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