nrs jayaram
nrs jayaram

Reputation: 3448

Java Swing: Images not Displaying when run from jar file

Swing application and it's Images are running fine in eclipse. but when i run from jar file, images not displaying. I tryed to load images in different way, but some time jar file not executing.

My image folder is inside of source folder.

I load my images with:

1.Running fine in eclipse, but not in jar

ImageIcon right = new ImageIcon("./chack img/Green Tick 1.PNG");

2.Running fine in eclipse, but jar file not executing.

ImageIcon wrong = new javax.swing.ImageIcon(getClass().getResource("/chack img/Red Cross1.PNG"));

I tryed some other code also, still my issue not solved.

Upvotes: 0

Views: 911

Answers (2)

SalaxDev
SalaxDev

Reputation: 1

import javax.swing.JFrame ;
import javax.imageio.ImageIO ;
import java.io.IOException ;
import java.awt.image.BufferedImage ;

public class LoadImage extends JFrame {
    public LoadImage() {
        setSize(600, 600) ;
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
        BufferedImage image = null ;
        try {
            image = ImageIO.read(getClass().getResourceAsStream("/path/to/your/location.png"));
        } catch(IOException e) {
            e.printStackTrace();
        }
        if (image != null) {
            setIconImage(image) ;
        }    
        setLocationRelativeTo(null) ;
    }
    
    public static void main(String[] args) {
        new LoadImage().setVisible(true) ;
    }
}

ImageIO.read(getClass().getResourceAsStream("/Path/to/your/image") this methode can help you load the image inside the jar, put your image inside the resources, for an example for your image name: "myImage.png or .jpg" the path would look like this: "/myImage.png"

Upvotes: 0

nathanfranke
nathanfranke

Reputation: 991

Put your images in the src folder, along with your classes. Optional, but make a package that stores your images. Compiling a jar file will not keep any directories that are not a source directory.

Also, remove all spaces from your folders and file names. This prevents confusion, and is likely part of your problem. No spacing is a good practice to follow in programming, and in most situations of naming folders and files.

Also, kiheru is correct, you should not have capital letters in the file extensions, for the same reason you should not have spaces; It can cause confusion and it is a bad practice in most cases.

EDIT: Simmilar Question

Upvotes: 1

Related Questions