0

I'm on a project where I have to display an image on jLabel on the click of a jButton. Now I want to display an image that is already imported into the project (src folder) and I don't want to use the path of the image file inside the .setIcon(path/image.png) method as the path of the image will surely change when I will run the program on an another pc. So is there anyway to do this?

Amit Khan
  • 9
  • 1

2 Answers2

-1

Try something like

JLabel jLabelName = new JLabel();

jLabelName.setIcon(new ImageIcon(PathtoImage));

sample:

new ImageIcon("C:\\java\button.jpg");
RyeRai
  • 118
  • 1
  • 2
  • 10
-1

Relative Path could resolve your issue. Image image = new ImageIcon(this.getClass().getResource("/assets/images/admin.png")).getImage();

Or

this.getClass().getClassLoader().getResource("/assets/images/admin.png")

but remember you should place your assets folder inside the src folder. Otherwise the assets folder is not contained in the program's .jar

  • hi, you can also set image form URL image = new ImageIcon(ImageIO.read(new URL("https://cdn1.iconfinder.com/data/icons/ecommerce-and-business-icon-set/128/admin.png"))); – Hasanuzzaman Rana Nov 05 '17 at 08:50