Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java adding ImageIcon to JLabel

I am trying to make a very basic game with Java and I am having trouble displaying an image on a JFrame. It has worked in the past for me and now is not, i can't see what I did wrong.

I have tried printing the current working directory and changing where I get my image to match that. It is likely that the problem is not getting the image, since my (filefinder or filereader or something like that) can find it without problems, but I cannot correctly add it (the ImageIcon) to the JLabel, or that to the JFrame.

This is my code...

JFrame frame = new JFrame("no image");
ImageIcon image = new ImageIcon("C:/Documents and Settings/user/Desktop/hi/xD/JavaApplication2/image.png");
JLabel imagelabel = new JLabel(image);
frame.add(imagelabel);

The JFrame has been setVisible(true) and pack().

Could someone please help me understand what is wrong.

like image 567
user1486826 Avatar asked Jun 28 '12 11:06

user1486826


2 Answers

Your problem lies here:

   ImageIcon image = new ImageIcon("C:/Documents and Settings/user/Desktop/hi/xD/JavaApplication2/image.png");
   JLabel imagelabel = new JLabel(character);

You create an ImageIcon "image" but you create your JLabel with "character".

It should be:

JLabel imagelabel = new JLabel(image);
like image 104
Guillaume Polet Avatar answered Sep 19 '22 15:09

Guillaume Polet


Try,

ImageIcon image = new ImageIcon("c:\\path\\image.png");
imagelabel = new JLabel(character, image, JLabel.CENTER);
frame.add(imagelabel);

Take a look at Tutorial - How to use Icons

like image 44
KV Prajapati Avatar answered Sep 20 '22 15:09

KV Prajapati