Setting Background Image in JFrame - Swing

Here is sample tutorial, a simple trick that enables you to set background image for JFrame.



import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame
{
JButton b1;
JLabel l1;
public BackgroundImageJFrame()
{
setTitle("Background Color for JFrame");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
/*
One way
-----------------
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
background.add(l1);
background.add(b1);
*/
// Another way
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png")));
setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
add(l1);
add(b1);
// Just for refresh :) Not optional!
setSize(399,399);
setSize(400,400);
}
public static void main(String args[])
{
new BackgroundImageJFrame();
}
}
 Notes: 

The first way: Here i have taken a JLabel named background and an image icon to it and then set the layout of the frame as BorderLayout so that it appears whole window.And then, i have added the label background to the frame. Next, some components are added to the label background instead of the frame and the layout for the background label is set as FlowLayout so that the components come side by side from the starting of the frame.

The second way: Here i used the setContentPane(Container c) method, which means to set the container (the one that contains the components) to the frame. As JLabel being one of the sub-classes of the Container, i have used it, added an image icon to it. You could also note, the BorderLayout which is set in order to make the image spread on the whole frame Next, as usual i have changed the layout for the frame and then added components to it.

The Refresh: This is essential because, the background image will not visible when the frame is opened. So, we will need to refresh it. So, i have called the setSize(int w,int h) twice which resizes (i.e. refreshes) the frame so that the background image will be visible.