Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem using image from other local package

Tags:

java

swing

jlabel

I have a JLabel in the frame which I want to have different images when clicked upon different buttons. Achieving this was easy. Here is the code

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

The problem i0,s earlier I was providing full path to the image like C:\Documents\xxx. Now when I tried the jar in some other computer I noticed the images are not used, that was obvious as the path assigned doesn't exist in other computer.

Back at project I have 2 packages, one for images called images and other for source files called smartshopping. I tried using couple of code but was not able to call the image from the package "images". Please help me fixing the problem. The project works fine in "my" computer if I provide 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 working as of now. What am I doing wrong. Package of image is named images.

like image 283
Shashwat Avatar asked Feb 23 '23 07:02

Shashwat


1 Answers

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

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

BTW, you're making it unnecessarily complex. No need to read the image using ImageIO or to flush the image. Just do

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

Note: I prefer hardcoding Foo.class rather than using getClass(), because getClass() will return another class if it's called by a subclass, and the relative path will thus point to another location which, most of the time, is not what is desired.

like image 90
JB Nizet Avatar answered Mar 07 '23 17:03

JB Nizet