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.
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.
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"); add(b); pack();
Include the code in the constructor of JFrame.
And then you can add components on to the JFrame.
Latest posts by Amit Rawat (see all)
- Python Program to Display or Print Prime Numbers Between a Range or an Interval - June 18, 2019
- Python Program To Print Pascal’s Triangle (2 Ways) - June 17, 2019
- Python program to print Floyd’s Triangle (3 Ways) - June 15, 2019