7

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

mKorbel
  • 108,320
  • 17
  • 126
  • 296
Matthew G
  • 95
  • 1
  • 1
  • 9
  • 3
    You'll want to search this site as this has been asked a lot. if you're looking to access an image from a jar file, then you'll want to do it as a resource, i.e., `ImageIO.read(getClass().getResourceAsStream(resourcePath));` The resources path will be relative to your class files. – Hovercraft Full Of Eels Mar 29 '13 at 21:40
  • Note: ImageIcon is *not* a "good fix". – Hovercraft Full Of Eels Mar 29 '13 at 23:14

1 Answers1

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

MadProgrammer
  • 323,026
  • 21
  • 204
  • 329