Domanda

I am attempting to set an image to a JLabel and within my project I have a folder "images", within that is the logo.png

I am using the following code to get it

BufferedImage myPicture = null;

    try {
        myPicture = ImageIO.read(new File("images/logo.png"));
    } catch (IOException e1) {

        e1.printStackTrace();
    }

    JLabel headerImage = new JLabel(new ImageIcon(myPicture));

This works file within eclipse, however outside the runnable jar wont fire unless it is in the same directory as the folder images with the logo file within.

So my question is how can i pack the image within the .jar file and have this code reference it?

È stato utile?

Soluzione

You need to get it from the classpath instead of from the local disk file system.

Assuming that images is actually a package and that this package is inside the same JAR as the current class, then do so:

BufferedImage myPicture = null;
try {
    myPicture = ImageIO.read(getClass().getResource("/images/Report.png"));
} catch (IOException e1) {

    e1.printStackTrace();
}

JLabel headerImage = new JLabel(new ImageIcon(myPicture));

Altri suggerimenti

Try this have been works for me fine

   ImageIO.read(getClass().getResource("images/logo.png"));

You can read the image file from the classpath using something like this:

this.getClass().getResourceAsStream("logo.png");

Take a look at this blog post for a complete example.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top