Adding a background image to a JPanel

Matthew G picture Matthew G · Mar 29, 2013 · Viewed 13.3k times · Source

I'm working on building a board game in Java. For the game board itself I was trying to place the image of the board as the background of the entire JPanel, which fills the JFrame. I found a way to do this, but only with the file stored locally, it needs to be able to take the image from the package the GUI is inside as well.

package Gui;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

//Proof of concept for setting an image as background of JPanel

public class JBackgroundPanel extends JPanel {
    private BufferedImage img;

    public JBackgroundPanel() {
        // load the background image
        try {
            img = ImageIO.read(new File(
                    "C:\\Users\\Matthew\\Desktop\\5x5     Grid.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        // paint the background image and scale it to fill the entire space
        g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
    }
}

I've read that using ImageIcon is a good fix, but I don't know how to use it properly.

Edit 1 - I found my answer here http://www.coderanch.com/how-to/java/BackgroundImageOnJPanel I also had the picture formatted wrong in my workspace. Thanks for the help

Answer

MadProgrammer picture MadProgrammer · Mar 29, 2013
  1. Make sure the resource you want to load is located within the Jar file
  2. Use getClass().getResource("/path/to/resource") to obtain a URL reference to the resource, which can be used by ImageIO to read the resource

So, for example, if the image was located in the /images folder inside your Jar, you could use

 ImageIO.read(getClass().getResource("/images/5x5    Grid.jpg"));

For example...