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:

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main extends JFrame {

    public static void main(String[] args0) {

        JFrame frame = new JFrame();
        ImageIcon image = new ImageIcon("background.bmp");
        JLabel imageLabel = new JLabel(image);
        frame.add(imageLabel);
        frame.setLayout(null);
        imageLabel.setLocation(0, 0);
        imageLabel.setSize(1000, 750);
        imageLabel.setVisible(true);
        frame.setVisible(true);
        frame.setSize(1000, 750);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);

    }

}

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)

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.

import java.awt.Image;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main extends JFrame {

    public static void main(String[] args0) {

        try {
            JFrame frame = new JFrame();
            File imageFile = new File("background.bmp");
            Image i = ImageIO.read(imageFile);
            ImageIcon image = new ImageIcon(i);
            JLabel imageLabel = new JLabel(image);
            frame.add(imageLabel);
            frame.setLayout(null);
            imageLabel.setLocation(0, 0);
            imageLabel.setSize(1000, 750);
            imageLabel.setVisible(true);
            frame.setVisible(true);
            frame.setSize(1000, 750);
            frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

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.



Source: stackoverflow