• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 674
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Rancher
Posts: 3324
32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Rancher
Posts: 3324
32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Rob

Link has solved my problem
reply
    Bookmark Topic Watch Topic
  • New Topic