Skip to main content

How to set a background image to a jFrame?




If you are using Netbeans IDE or windowbuilder in Eclipse to develop Swing GUIs, you might wanted to set background images to jFrames.

The easiest way is putting a jLabel to cover whole jFrame and set an image to it. It might be ok Absolute layout but if you are using  something like SpringLayout this will not work. And also there might be problems with re-sizing the jFrame.

Instead of that what we are going to do is put a jPanel to cover up the whole jFrame and set a background image to it.

in Eclipse WindowBuilder

I have already installed WindowBuilder plugin in my Eclipse and created a java project.
And I have created a new jFrame form with WindowBuilder.
(If you are not familiar with eclipse and windowbuilder please google it and read first)


Here is the code for MyFrame class which is automatically created by windowbuilder
1:  package org.jframebg;  
2:  import java.awt.BorderLayout;  
3:  import java.awt.EventQueue;  
4:  import javax.swing.JFrame;  
5:  import javax.swing.JPanel;  
6:  import javax.swing.border.EmptyBorder;  
7:  public class MyFrame extends JFrame {  
8:       private JPanel contentPane;  
9:       /**  
10:        * Launch the application.  
11:        */  
12:       public static void main(String[] args) {  
13:            EventQueue.invokeLater(new Runnable() {  
14:                 public void run() {  
15:                      try {  
16:                           MyFrame frame = new MyFrame();  
17:                           frame.setVisible(true);  
18:                      } catch (Exception e) {  
19:                           e.printStackTrace();  
20:                      }  
21:                 }  
22:            });  
23:       }  
24:       /**  
25:        * Create the frame.  
26:        */  
27:       public MyFrame() {  
28:            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
29:            setBounds(100, 100, 450, 300);  
30:            contentPane = new JPanel();  
31:            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));  
32:            contentPane.setLayout(new BorderLayout(0, 0));  
33:            setContentPane(contentPane);  
34:       }  
35:  }  


Adding the background image

In my project, I created a new package called images and placed my background image bg.jpg inside it.


Now let's set up the image in jFrame !

We can see in the above code windowbuilder has already created a jPanel and added it to the jFrame for us.

8:      private JPanel contentPane;  

30:     contentPane = new JPanel();   

Now let's modify that code a little bit.
What we are going to do is, override the paintComponent() method of the jPanel and draw the image in it.
Here in the line 33MyFrame should be the class name of the jFrame.

30:  contentPane = new JPanel() {  
31:                 public void paintComponent(Graphics g) {  
32:                      Image img = Toolkit.getDefaultToolkit().getImage(  
33:                                MyFrame.class.getResource("/images/bg.jpg"));  
34:                      g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);  
35:                 }  
36:            };  

And we have to import some classes as well.

 import java.awt.Graphics;  
 import java.awt.Image;  
 import java.awt.Toolkit;  

Now the background image is done.
Here is our final code.

1:  package org.jframebg;  
2:  import java.awt.BorderLayout;  
3:  import java.awt.EventQueue;  
4:  import java.awt.Graphics;  
5:  import java.awt.Image;  
6:  import java.awt.Toolkit;  
7:  import javax.swing.JFrame;  
8:  import javax.swing.JPanel;  
9:  import javax.swing.border.EmptyBorder;  
10:  public class MyFrame extends JFrame {  
11:       private JPanel contentPane;  
12:       /**  
13:        * Launch the application.  
14:        */  
15:       public static void main(String[] args) {  
16:            EventQueue.invokeLater(new Runnable() {  
17:                 public void run() {  
18:                      try {  
19:                           MyFrame frame = new MyFrame();  
20:                           frame.setVisible(true);  
21:                      } catch (Exception e) {  
22:                           e.printStackTrace();  
23:                      }  
24:                 }  
25:            });  
26:       }  
27:       /**  
28:        * Create the frame.  
29:        */  
30:       public MyFrame() {  
31:            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
32:            setBounds(100, 100, 450, 300);  
33:            contentPane = new JPanel() {  
34:                 public void paintComponent(Graphics g) {  
35:                      Image img = Toolkit.getDefaultToolkit().getImage(  
36:                                MyFrame.class.getResource("/images/bg.jpg"));  
37:                      g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);  
38:                 }  
39:            };  
40:            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));  
41:            contentPane.setLayout(new BorderLayout(0, 0));  
42:            setContentPane(contentPane);  
43:       }  
44:  }  


If you run the code, window will appear with your background. And no matter how you resize it, the background will also be resized with the window.



in Netbeans IDE

Same as above I have already created new java project and a jFrame in it.
And also I have placed my image in the images package.


First we set the layout of the jFrame to Free Design, which is the default layout.
Right click -> Set Layout -> Free Design



Then we add a jPanel over the jFrame.
And stretch it to cover up the whole surface of the jFrame.


Now again we are going to modify the code.
But if you look in the source tab, the auto generated code cannot be edited.
Here is how it look like the auto generated code where our jPanel instantiated.


Now let's see how to modify the instantiated code of the jPanel :

Go back go the design go to the properties window of the jPanel.
Right click -> Properties
Click on the Code  tab of the properties window and find the "Custom Creation code" in it.


Click on the tiny button in the right corner of "Custom Creation Code" property.
Then we will be prompted to add our own custom creation code for the jPanel.
Thus we can modify the code to override the paintComponent() method of the jPanel to draw the background image.


 new JPanel() {  
   public void paintComponent(Graphics g) {  
     Image img = Toolkit.getDefaultToolkit().getImage(  
     MyFrame.class.getResource("/images/bg.jpg"));  
     g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);  
     }  
   };  
Here MyFrame is the class name of the jFrame.

Press ok and close out the properties window.
Now, if we check the auto generated code, it is changed to the new code we customized.


And don't forget to import these classes.

 import java.awt.Graphics;  
 import java.awt.Image;  
 import java.awt.Toolkit;  
 import javax.swing.JPanel;  

Now run the file, you will get the background image that resize with the jFrame.


Comments

Post a Comment

Popular posts from this blog

Install Docker on Windows 11 with WSL Ubuntu 22.04

This is to install Docker within Ubuntu WSL without using the Windows Docker application. Follow the below steps. Install Ubuntu 22.04 WSL 1. Enable Windows Subsystem for Linux and Virtual Machine platform Go to Control Panel -> Programs -> Programs and Features -> Turn Windows features on or off 2. Switch to WSL 2 Open Powershell and type in the below command. wsl --set-default-version 2 If you don't have WSL 2, download the latest WSL 2 package and install it.  3. Install Ubuntu Open Microsoft Store and search for Ubuntu. Select the version you intend to install. I'd use the latest LTS version Ubuntu 22.04. Click on the Get button. It will take a couple of minutes to download and install. 4. Open up the installed Ubuntu version that was installed. If you get an error like the below image, make sure to install the WSL2 Kernel update .  If it's an older Ubuntu version the error message would be something like the image below. Error: WSL 2 requires an update to its

Wget download pause and continue

If you are downloading a file with the wget command, sometimes you may need to pause it and start it back from the place where you paused rather than starting from the beginning. So you don't have to re-download the entire package. Wget can do this just like downloading from a web browser. Let's say I need to download a file from the web. So I'm using the wget command as follows. Download wget <url for the file> Pause To pause the download just hit ctrl + c  the shortcut to terminate the current command. Continue This is going to be the same command but -c switch to continue from the previous download. wget -c <url for the file> Simple as that! Yeah, you can download from a web browser, but this is more fun and easier 😋 If you are lazy like me, wget saves a couple of clicks.

How to fix SSLHandshakeException PKIX path building failed in Java

TL ; DR 1. Extract the public certificate of the website/API that you are trying to connect from your Java application. Steps are mentioned in this post 2. Use the Java keytool to install the extracted certificate into the "cacerts" file (Trust store) keytool -import -trustcacerts -alias <domain name> -file <public certificate>.cert -keystore /path_to_java_home/jre/lib/security/cacerts -storepass changeit 3. Restart your Java application Exception A typical exception stack trace would look like below. javax.net.ssl. SSLHandshakeException : sun.security.validator.ValidatorException: PKIX path building failed : sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1959) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302) at sun.security.ssl.Handshake