Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a background image to a JPanel

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

like image 517
Matthew G Avatar asked Mar 29 '13 21:03

Matthew G


1 Answers

  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...

like image 117
MadProgrammer Avatar answered Oct 12 '22 23:10

MadProgrammer