Pergunta

I created a java app and I put some images in it and even gave it an image icon as the desktop image, but when i made it a jar file, and put it on another pc, all images were gone. This is the image path :

 File imageFile = new File("C:\\Users\\Favour's Computer\\workspace\\Physics Calculator\\src\\res\\icon.jpg");

I checked it online and i found out that the problem is that i got the file through the C:\\ directory, they said the image file should look like this :

 File imageFile = new File("res/icon.jpg");

I tried this but it didnt work, I kept getting an error message like : file not found

This is my full code :

BufferedImage image = null;
try {
File imageFile = new File("C:\\Users\\Favour's Computer\\workspace\\Physics Calculator\\src\\res\\icon.jpg");
        image = ImageIO.read(imageFile);
    } catch(IOException e) {
        e.printStackTrace();
    }

    setIconImage(image);

Please, i have been trying to solve this for weeks, do anyone know how i can solve this, please if you do, please help

Foi útil?

Solução

The images should not be loaded from the file system, but should be bundled into the app, inside your jar.

If you put the image foo.png inside the jar, under the package com.bar.resources for example, you simply need to use

InputStream in = getClass().getResourceAsStream("/com/bar/resources/foo.png")

to load the image as an input stream.

That will use the class loader to load the image. So, during development, if you're using a standard IDE project, you just need to put the image file in the appropriate package in your source directory: the IDE will "compile" the file by copying it to the same directory as the generated .class files. If you're using a standard Maven/Gradle project, then it needs to be put in the appropriate package under src/main/resources.

Outras dicas

Problem is you dont have res folder in your project, first of create a folder a "res" by Right Clicking on project and place the image icon.jpg image in that "res". and

use : `File imageFile = new File("res/icon.jpg");`// To retrieve image to your project.

You cannot retrieve the image from your local system, because it is not attached with your projects workspace.

There are two options....

1)Either make res a "source folder" . You will know this if you are using Eclipse. Then you can use like

ImageIO.read(new File("res/icon.jpg"));

2) If res is a normal folder, you will have to use. In this case res will be considered as a package

ImageIO.read(new File("src/res/icon.jpg"));
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top