title: Adding a background image to a JPanel
body: <p>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.  </p>
  
  <pre><code>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);
      }
  }
  </code></pre>
  
  <p>I've read that using ImageIcon is a good fix, but I don't know how to use it properly.</p>
  
  <p>Edit 1 - I found my answer here 
  <a href="http://www.coderanch.com/how-to/java/BackgroundImageOnJPanel" rel="noreferrer">http://www.coderanch.com/how-to/java/BackgroundImageOnJPanel</a> 
  I also had the picture formatted wrong in my workspace.  Thanks for the help </p>