• 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

How do I display an image on a JLabel

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am having trouble trying to display an image on a JLabel.
The code I have been trying is as follows:
ImageIcon icon = new ImageIcon ("airplane4.gif");
System.out.println("Size of the Image = " +
icon.getIconHeight() + "..." +
icon.getIconWidth());
if (icon == null) {
System.out.println("Icon not loaded");
} else {
System.out.println("Icon loaded = " + icon);
}
JLabel imageLabel = new JLabel(icon);
When I try to display the loaded images's width and height, I get -1 as the reply + The image is also not displayed.
Any idea as to where I am going wrong will be much appreciated.
Thanks,
 
Ranch Hand
Posts: 269
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It looks like your image is not loaded. Are you sure that the path to the image is in your classpath?
W.
 
Sowjanya Raghu
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The image is definitely getting loaded 'cause when I run the code "Icon loaded = " + icon is displayed.
But the return values of getIconHeight() and getIconWidth() are
-1.
I wonder if I have to do something else.
Thanks for the reply,
S
 
Ranch Hand
Posts: 2823
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your icon is not getting loaded. I just used your code with a non-existent image and it followed the loaded path. Changed it to a valid one and it works fine. The way you have the image loaded it must exist in the same directory as the class file that is running. Check where your image is and where your class file is and change
ImageIcon icon = new ImageIcon ("airplane4.gif");
to match this.
 
There's a way to do it better - find it. -Edison. A better tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic