Question

I am trying to display an image in my swing application and cannot seem to do so without absolute file addressing. This is a problem because I need to be able to give this program to others to use, and cannot have it addressed just to my computer. The code that loads the image is below:

public void loadImage(){
    try{
        BufferedImage img = ImageIO.read(new File("mock logo 128x128.png"));
        logoImage = new JLabel(new ImageIcon(img));
    }
    catch(IOException e){
        System.out.println("Logo not found");
        e.printStackTrace();
    }
}

I am certain that the file is in the src folder, so I know that is not the problem. if I setup the code like this:

public void loadImage(){
    try{
        BufferedImage img = ImageIO.read(new File("C:\\Users\\Dan\\Documents\\EXSoft\\ExSoft Workspace\\Septic Calculator Alpha\\src\\mock logo 128x128.png"));
        logoImage = new JLabel(new ImageIcon(img));
    }
    catch(IOException e){
        System.out.println("Logo not found");
        e.printStackTrace();
    }
}

Everything works perfectly. But as previously stated, this is not an acceptable solution.

Was it helpful?

Solution

You put the file in the src folder, therefore its packaged as part of your app. Its not outside your app binary. therefore you must use ClassLoader#getResourceAsStream.

Example:

    BufferedImage img = ImageIO.read(YourClass.class.getClassLoader().getResourceAsStream("mock logo 128x128.png"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top