How to set a background image in java

Having the plain background makes the project look old fashion. So I am writing this post to tell how to set a background image in a java project.

Firstly I discuss how it will be done on an IDE like Netbeans and then how it will be done using code.

Setting background image using Netbeans IDE

Create a JFrame form file and set the layout of the JFrame to Absolute Layout.


Now add a JLabel to store the image, which will act as the background later.

Click here to know how to add an image in java.


After adding the image and resizing it to the desired size(it should be of the JFrame size).

You can add other components to it but you will notice that it will not be visible as you add it to the JFrame.

component disappeare

Actually, it is behind the JLabel on which the image is set. So to get the component in front of the JLabel, we have to move the JLabel to the back.

To do that left click on the image JLabel then select "Move Down". Now the component will be visible.


This way you can create a JFrame having any number of components with a cool background.

background image

background image

Now let's see how it will be done using code.

Setting background image using Code

Using this method is quite easy and smooth. You just have to add a small code snippet and you are good to go.

Use this code to put a background image on the JFrame.

 setContentPane(new JLabel(new ImageIcon("F:\\spiderlab\\netbeans data\\Projects\\spiderlabweb\\src\\spiderlabweb\\pic.png")));
 setLayout(new FlowLayout());
 JButton b = new JButton("hello spider");

Include the code in the constructor of JFrame.

java code

And then you can add components on to the JFrame.

background image

The following two tabs change content below.

Amit Rawat

Founder and Developer at SpiderLabWeb
I love to work on new projects and also work on my ideas. My main field of interest is Web Development.

You may also like...