Setting background images in JFrame

Are any methods available to set an image as background in a JFrame?


There is no built-in method, but there are several ways to do it. The most straightforward way that I can think of at the moment is:

  1. Create a subclass of JComponent.
  2. Override the paintComponent(Graphics g) method to paint the image that you want to display.
  3. Set the content pane of the JFrame to be this subclass.

Some sample code:

class ImagePanel extends JComponent {
    private Image image;
    public ImagePanel(Image image) {
        this.image = image;
    protected void paintComponent(Graphics g) {
        g.drawImage(image, 0, 0, this);

// elsewhere
BufferedImage myImage =;
JFrame myJFrame = new JFrame("Image pane");
myJFrame.setContentPane(new ImagePanel(myImage));

Note that this code does not handle resizing the image to fit the JFrame, if that's what you wanted.

Try this :


import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Test {

    public static void main(String[] args) {
        JFrame f = new JFrame();
        try {
            f.setContentPane(new JLabel(new ImageIcon( File("test.jpg")))));
        } catch (IOException e) {


By the way, this will result in the content pane not being a container. If you want to add things to it you have to subclass a JPanel and override the paintComponent method.

You can use the Background Panel class. It does the custom painting as explained above but gives you options to display the image scaled, tiled or normal size. It also explains how you can use a JLabel with an image as the content pane for the frame.

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

class BackgroundImageJFrame extends JFrame

    JButton b1;
    JLabel l1;

    public BackgroundImageJFrame() {


        setLayout(new BorderLayout());

        JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful_design.png"));


        background.setLayout(new FlowLayout());

        l1=new JLabel("Here is a button");
        b1=new JButton("I am a button");


    public static void main(String args[]) 
        new BackgroundImageJFrame();

check out the below link

Need Your Help

How to maintain the open/closed principle with inheritance hierarchies of objects in containers?


When I want to add functionality to this structure, without changing it:

Xcode 3.2.2 and LLVM version 1.0.2 failing

iphone xcode

I have Xcode 3.2.2 and I am trying to use LLVM version 1.0.2 as a compiler.