Problem using image from another local package

I have JLabel in a frame that I want to have different images when I click on different buttons. This was easy to achieve. Here is the code

ImageIcon icon = new ImageIcon (img); icon.getImage().flush(); shopBanner.setIcon(icon); 

Problem i0, s I used to provide the full path to the image, for example, C: \ Documents \ xxx. Now, when I tried the jar on another computer, I noticed that the images were not being used, this was obvious since the assigned path does not exist on the other computer.

In the project, I have 2 packages, one for images called images and another for source files called smartshopping. I tried using a couple of codes, but could not call the image from the "image" package. Please help me solve the problem. The project works fine on my computer if I provide the full path as C: / Docs ....

Here is the code

  Image img = ImageIO.read(getClass().getResource("images/bb-banner-main.jpg")); ImageIcon icon = new ImageIcon (img); icon.getImage().flush(); shopBanner.setIcon(icon); 

I even tried

  URL img= this.getClass().getResource("images/icon.png"); ImageIcon imageIcon = new ImageIcon(img); //icon.getImage().flush(); shopBanner.setIcon(imageIcon); 

Nothing is working at the moment. What am I doing wrong. An image package is called images.

+4
source share
1 answer

Foo.class.getResource("images/icon.png") considers images/icon.png as a relative path to Foo.class . Therefore, if Foo is in the com.bar package, it will look for com/bar/images/icon.png .

Place a slash at the beginning of the path to make it absolute (i.e. start at the root of the class path).

By the way, you make it unnecessarily complicated. No need to read the image using ImageIO or hide the image. Just do

 ImageIcon icon = new ImageIcon(Foo.class.getResource("/images/icon.png")); 

Note. I prefer hardcoding Foo.class instead of using getClass() , because getClass() will return another class if it calls a subclass, and the relative path thus points to a different location, which in most cases is not desirable.

+8
source

All Articles