Skip to content
Advertisement

Java – How do I get an image to display?

I have spent a really long time trying to find a way to display an image in a Java program (I’m trying to learn how to make a 2D Java game) an nothing that I’ve tried works. I’m using Eclipse Mars and the latest of everything else. Here is my code:

JavaScript

Please, just tell me how to correct the code so that the image actually displays. Thank you ahead of time.

(P.S. the “background.bmp” file is in the “default package” if that changes anything)

Advertisement

Answer

The image with .bmp suffix can’t be displayed in your code. Try to modify

ImageIcon image = new ImageIcon(“background.bmp”);

to

ImageIcon image = new ImageIcon(“background.png”);

and change the image name to background.png.

However, if you just want to use background.bmp, you need to modify your code like this and background image will be displayed.

JavaScript

Here is the effect with new code: enter image description here

Hope it helps.

BTW, I’ve put the image at the root directory of the project.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement