How to add background Image to JFrame in Java


To add background image to JFrame, use the getImage() method of the Image class −

Image img = Toolkit.getDefaultToolkit().getImage("E:\rahul.jpg");

Now, draw the image −

public void paintComponent(Graphics g) {
   super.paintComponent(g);
   g.drawImage(img, 0, 0, null);
}

The following is an example to add Background Image to JFrame −

Example

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.IOException;
import javax.swing.JPanel;
public class SwingDemo extends javax.swing.JFrame {
   Image img = Toolkit.getDefaultToolkit().getImage("E:\rahul.jpg");
   public SwingDemo() throws IOException {
      this.setContentPane(new JPanel() {
         @Override
         public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(img, 0, 0, null);
         }
      });
      pack();
      setVisible(true);
   }
   public static void main(String[] args) throws Exception {
      new SwingDemo();
   }
}

Output

Updated on: 30-Jul-2019

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements