Displaying an image as the background of a JPanel

Override the JPanel’s method paintComponent, draw the image using g.drawImage and call the superclass’ paintComponent. Make sure the JPanel is opaque.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JPanel panel = createPanel();
 
      getContentPane().add(BorderLayout.CENTER, panel);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static JPanel createPanel() {
      JPanel panel = new JPanel() {
         public void paintComponent(Graphics g) {
            ImageIcon img = new ImageIcon("c:\mong.jpg");
            System.out.println(g.drawImage(img.getImage(), 0, 0, null));
            super.paintComponent(g);
         }
      };
      panel.setOpaque(false);
      panel.setLayout(new GridLayout(20, 4, 10, 10));
 
      for (int i=0; i<20; i++) {
         for (int j=0; j<4; j++) {
            JLabel label = new JLabel("label " + i + ", " + j);
            label.setFont(new Font("Helvetica", Font.PLAIN, 30));
            panel.add(label);            
         }
      }
 
      return panel;
   }
 
   public static void main(String [] args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   } 
} 

BTW, here’s the image I used: