How to add background Image to JFrame in Java

Java 8Object Oriented ProgrammingProgramming

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

raja
Published on 08-May-2019 16:12:23
Advertisements