简体   繁体   English

导出jar文件中的资源

[英]Export resource in jar file

I have a problem to export my Jframe app with the background resource into jar file (without any external resource folder. I prefer to have everything into jar file for better portability).我在将带有背景资源的 Jframe 应用程序导出到 jar 文件时遇到问题(没有任何外部资源文件夹。为了更好的可移植性,我更喜欢将所有内容都放入 jar 文件中)。 Here's the code.这是代码。 On Eclipse all work correctly, but when I export into jar file the app doesn't load because the resource "cccc.jpg" is not found.在 Eclipse 上一切正常,但是当我导出到 jar 文件时,应用程序不会加载,因为找不到资源“cccc.jpg”。 I have already tried the getResource() but it didn't work as well.我已经尝试过 getResource() 但效果不佳。

// Load Background image
BufferedImage img = null;
try {
    img = ImageIO.read(new File("cccc.jpg"));
} catch (IOException e) {
    e.printStackTrace();
}

// Set Background image
Image dimg = img.getScaledInstance(640, 480, Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(dimg);
setContentPane(new JLabel(imageIcon));

like

BufferedImage bufferedImage = ImageIO.read(MyClass.class.getResource("/images/cccc.jpg"));

see: Loading image from a resource Can't read input file请参阅: 从资源加载图像无法读取输入文件

Saying that your code works in ecplise is a hint that you have located the "cccc.jpg" file in the root of your project folder (this is the current folder when you run the application or a unit test within eclipse).说您的代码在 ecplise 中工作是暗示您已在项目文件夹的根目录中找到“cccc.jpg”文件(这是在 eclipse 中运行应用程序或单元测试时的当前文件夹)。

For having the file packed as resource into your jar: simply put it somewher into your source folder.要将文件作为资源打包到您的 jar 中:只需将其放入您的源文件夹中。 If you have your source packages named like "my.app.main" you could place your image file directly beside the your "my" folder and load it by:如果您的源包名为“my.app.main”,您可以将图像文件直接放在“my”文件夹旁边并通过以下方式加载:

InputStream is = ClassLoader.getSystemResourceAsStream( "cccc.jpg" )

Or place it into a sub package (eg "my.app.images") and load it by:或者将其放入子包(例如“my.app.images”)并通过以下方式加载:

InputStream is = ClassLoader.getSystemResourceAsStream( "my/app/images/cccc.jpg" )

BTW: ImageIO.read can also take an InputStream as parameter.顺便说一句:ImageIO.read 也可以将 InputStream 作为参数。

I solved the problem.我解决了这个问题。 Now everything is loaded correctly when I open the jar file.现在,当我打开 jar 文件时,一切都已正确加载。

Link to the picture of the problem solved链接到已解决问题的图片

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM