Having images as background of JPanel

I am new in Java and I am currently creating a game with graphics. I have this class that extends from JFrame. In this class, I have many JPanels that needs an image as background. As I know, to be able to paint images in the JPanel, I need to have a separate class that extends from JPanel and that class's paintComponent method will do the work. But I don't want to make separate classes for each JPanel, I have too many of them; and with the fact that I am only concerned with the background. How can I do this? is it with an anonymous inner class? How?

For better understanding I provided some code:

public GUI extends JFrame {
  private JPanel x;
  ...  

  public GUI() {
   x = new JPanel();
   // put an image background to x
  }

Solution 1:

Why not make a single class that takes a Image??

public class ImagePane extends JPanel {

    private Image image;

    public ImagePane(Image image) {
        this.image = image;
    }

    @Override
    public Dimension getPreferredSize() {
        return image == null ? new Dimension(0, 0) : new Dimension(image.getWidth(this), image.getHeight(this));
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.drawImage(image, 0, 0, this);
        g2d.dispose();
    }
}

You would even provide hints about where it should be painted.

This way, you could simply create an instance when ever you needed it

Updated

The other question is, why?

You could just use a JLabel which will paint the icon for you without any additional work...

See How to use labels for more details...

This is actually a bad idea, as JLabel does NOT use it's child components when calculating it's preferred size, it only uses the size of the image and the text properties when determining it's preferred size, this can result in the component been sized incorrectly

Solution 2:

You don't have to make another class for it? You could just do:

x = new JPanel(){
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        //draw background image
    }
};

Solution 3:

You can do this in single line:

panelInstance.add(new JLabel(new ImageIcon(ImageIO.read(new File("Image URL")))));

I hope it will work for you.