简体   繁体   中英

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). 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. I have already tried the getResource() but it didn't work as well.

// 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).

For having the file packed as resource into your jar: simply put it somewher into your source folder. 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:

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

Or place it into a sub package (eg "my.app.images") and load it by:

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

BTW: ImageIO.read can also take an InputStream as parameter.

I solved the problem. Now everything is loaded correctly when I open the jar file.

Link to the picture of the problem solved

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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