Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How do I display an image on a JLabel

 
Sowjanya Raghu
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • 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,
 
Wilfried LAURENT
Ranch Hand
Posts: 269
  • Mark post as helpful
  • send pies
  • 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
  • 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
 
Paul Stevens
Ranch Hand
Posts: 2823
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic