Java Swing How to - Add Background Image to JFrame








Question

We would like to know how to add Background Image to JFrame.

Answer

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.IOException;
/*from  w w w  .j  a v a2s.c  o m*/
import javax.swing.JPanel;

public class Main extends javax.swing.JFrame {
  Image backgroundImage = Toolkit.getDefaultToolkit().getImage("mong.jpg");

  public Main() throws IOException {
    this.setContentPane(new JPanel() {
      @Override
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(backgroundImage, 0, 0, null);
      }
    });

    pack();
    setVisible(true);
  }

  public static void main(String[] args) throws Exception {
    new Main();
  }
}