how to set an image as a background for frame in swing gui of java

how to set an image as a background for frame in swing gui of java  using -'java,swing'

I have created one GUI using Swing of Java. I have to now set one sample.jpeg image as a background to the frame on which I have put my components.How to do that ?

asked Sep 22, 2015 by rajeevr642
0 votes

4 Answers

0 votes

There is no concept of a "background image" in a JPanel, so one would have to write their own way to implement such a feature.

One way to achieve this would be to override the paintComponent method to draw a background image on each time the JPanel is refreshed.

For example, one would subclass a JPanel, and add a field to hold the background image, and override the paintComponent method:

public class JPanelWithBackground extends JPanel {

  private Image backgroundImage;

  // Some code to initialize the background image.
  // Here, we use the constructor to load the image. This
  // can vary depending on the use case of the panel.
  public JPanelWithBackground(String fileName) throws IOException {
    backgroundImage = File(fileName));

  public void paintComponent(Graphics g) {

    // Draw the background image.
    g.drawImage(backgroundImage, 0, 0, this);

(Above code has not been tested.)

The following code could be used to add the JPanelWithBackground into a JFrame:

JFrame f = new JFrame();
f.getContentPane().add(new JPanelWithBackground("sample.jpeg"));

In this example, the method was used to read in the external JPEG file.

answered Sep 22, 2015 by kinnari
0 votes
answered Sep 22, 2015 by abhi
0 votes

Here is another quick approach without using additional panel.

JFrame f = new JFrame("stackoverflow") { 
  private Image backgroundImage = File("background.jpg"));
  public void paint( Graphics g ) { 
    g.drawImage(backgroundImage, 0, 0, null);
answered Sep 22, 2015 by yogeshplv
0 votes

This is easily done by replacing the frame's content pane with a JPanel which draws your image:

try {
    final Image backgroundImage = File(...));
    setContentPane(new JPanel(new BorderLayout()) {
        @Override public void paintComponent(Graphics g) {
            g.drawImage(backgroundImage, 0, 0, null);
} catch (IOException e) {
    throw new RuntimeException(e);

This example also sets the panel's layout to BorderLayout to match the default content pane layout.

(If you have any trouble seeing the image, you might need to call setOpaque(false) on some other components so that you can see through to the background.)

answered Sep 22, 2015 by deepak07.s