William Falcon
William Falcon

Reputation: 9813

Load image in jar, error in code

I want to reference an image in my project that I will package into a Jar file.

This code is not working:

ImageIcon image = new ImageIcon("Images/buttonBackgroundSelected.png");

Any ideas? thanks

Upvotes: 0

Views: 76

Answers (1)

Reimeus
Reimeus

Reputation: 159754

This constructor only works if the image is available in the file system outside the JAR file

new ImageIcon("Images/buttonBackgroundSelected.png");

You almost never want to do this. You could use:

ImageIcon imageIcon = 
   new ImageIcon(getClass().getResource("/Images/buttonBackgroundSelected.png"));

when the folder and image and the have been included in the JAR file.

However, loading images this way fails silently if any issues loading the image. Therefore use ImageIO.read should be used:

Image image = 
   ImageIO.read(getClass().getResource("/Images/buttonBackgroundSelected.png"));

The resultant image can be wrapped in an ImageIcon if required.

Upvotes: 2

Related Questions