• Post Reply Bookmark Topic Watch Topic
  • New Topic

Is it possible to display image from relative URL in ImageIcon in Swing?

 
Kishor Joshi
Ranch Hand
Posts: 674
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there

I am using JButton class in Java Swing Application
My Requirement I want to set Image on a Button

So I try to plan use ImageIcon for this task

here is my code


I have stored all my Images inside the Images directory in my project but how to load Images from images folder to ImageIcon?


Thanks
 
Rob Camick
Ranch Hand
Posts: 2700
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That should work assuming you specified the path correctly. However it is not a good idea to hardcode a full path like that.

Instead you should load the image as a resource. Then the directories in your classpath will be searched to find the image. Read the section from the Swing tutorial on How to Use Icons for more information and examples.
 
Kishor Joshi
Ranch Hand
Posts: 674
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is my code

when I try to load Images from sub directory


its not working
attched is my project structure
directory.PNG
[Thumbnail for directory.PNG]
 
Rob Camick
Ranch Hand
Posts: 2700
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


When I compile from the command line I use:



without the leading space.

It looks like you are using an IDE so I think you need to use an absolution path like your original code (which is not a good idea), or you need to load the image as a resource as explained in the tutorial link I provided you.
 
Kishor Joshi
Ranch Hand
Posts: 674
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob

Link has solved my problem
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!