Displaying an image in your Java Program
- Put the image you want on your computer's desktop. This can be a .JPG, .PNG, .GIF or .BMP file. I would highly discourage BMP files because of their size.
- Drag the image file into Eclipse and drop it onto your project folder. This has an icon next to it that looks like a folder and has a small 'J' on it.
- Place the method (below these instructions) inside your Java program. DO NOT put it inside another method. It should be in the class. It is a method which means it should be pasted at the class level. Still unsure? Find your playGame method and paste it above the playGame method, but after the makeProgramWait method ends.
- In your constructor or newGame method, add the following line: 'image = readImage("mortland.jpg");'
- In your paintScreen method, add the following line: 'g.drawImage(image, <x>, <y>);' where <x> is the x-Coordinate and <y> is the y-Coordinate of the top left corner of the image you want to display.
- Your photo should now appear on the screen
public static Image readImage(String imageName)
{
Image i = Toolkit.getDefaultToolkit().getImage(imageName);
MediaTracker imageTracker = new MediaTracker(new JPanel());
imageTracker.addImage(i, 0);
try
{
imageTracker.waitForID(0);
}
catch(InterruptedException e)
{
return null;
}
return i;
}
{
Image i = Toolkit.getDefaultToolkit().getImage(imageName);
MediaTracker imageTracker = new MediaTracker(new JPanel());
imageTracker.addImage(i, 0);
try
{
imageTracker.waitForID(0);
}
catch(InterruptedException e)
{
return null;
}
return i;
}
Why doesn't my image appear on the screen
- Your image is not in the project folder. You may have placed it in the src or default package folder. Make sure you dropped it into the Java project folder.
- You misspelled the name of the file when you called the readImage method. Case matters!
- Your x and y coordinates are set to a location not on the screen