Java 如何使用eclipse在jar文件中包含所有图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6373021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:25:51  来源:igfitidea点击:

How to includes all images in jar file using eclipse

javaeclipsejar

提问by sAaNu

I made a java application and bundled all classes in a jar file. When I run the project from eclipse, my application is running successfully. But when I try to run my .jarfile, I am not getting the icons used by my application. In the code I get my icons from images directory present in project folder. How can I present these image files to the end user when using a jar?

我制作了一个 java 应用程序并将所有类捆绑在一个 jar 文件中。当我从 Eclipse 运行项目时,我的应用程序运行成功。但是当我尝试运行我的.jar文件时,我没有得到我的应用程序使用的图标。在代码中,我从项目文件夹中的图像目录中获取我的图标。使用 jar 时如何将这些图像文件呈现给最终用户?

I am loading the image like so:

我正在像这样加载图像:

 final public ImageIcon iReport=new ImageIcon("images/Report.png");

I have also tried

我也试过

final public ImageIcon iquit=new ImageIcon(getClass().getResource("images/quit.png"));

and

final public ImageIcon iquit=new ImageIcon(getClass().getResource("/images/quit.png"));

But this results in an error:

但这会导致错误:

Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)

采纳答案by BalusC

You need to get it from the classpath instead of from the local disk file system.

您需要从类路径而不是从本地磁盘文件系统获取它。

Assuming that imagesis actually a package and that this package is inside the same JAR as the current class, then do so:

假设它images实际上是一个包,并且该包与当前类位于同一个 JAR 中,然后执行以下操作:

final public ImageIcon iReport = 
    new ImageIcon(getClass().getResource("/images/Report.png"));

回答by gotomanners

The files in jar files are treated as "Resources". you need to access them as a classpath resource, regular File access methods does not work there.

jar 文件中的文件被视为“资源”。您需要将它们作为类路径资源访问,常规文件访问方法在那里不起作用。

Try this:

尝试这个:

final public ImageIcon iReport = (new ImageIcon(getClass().getResource("images/Report.png")));

回答by Velja

I know this was asked long ago, but it might help others with the same problem, like me. I was already using getClass().getResource("..."), but the resource didn't get exported with .jar file. I solved the problem by refreshing the 'Resources' folder, and its every subfolder.

我知道很久以前就有人问过这个问题,但它可能会帮助其他有同样问题的人,比如我。我已经在使用 getClass().getResource("..."),但是资源没有通过 .jar 文件导出。我通过刷新“资源”文件夹及其每个子文件夹解决了这个问题。

回答by SorcerOK

100% works

100% 有效

final public ImageIcon iReport = new ImageIcon(getClass().getResource("/Report.png"));

Don't forget about "/" at pathfor image.

不要忘记path图像的“/” 。