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

Java, how to create a list with a single element

 I wanted to create a Java List with a single element. Yet, I wanted to add more elements later. So, I was looking for a couple of ways to do this. So far there are multiple elegant ways to create a list with a single element with a one-liner. Not so much for a modifiable list though. Here's what I gathered so far. Followings are a few ways of creating a list with strictly a single entry. Can't add more elements. 1. Collections.singletonList() This returns an immutable list that cannot be modified or add more elements. // An immutable list containing only the specified object. List<String> oneEntryList = Collections. singletonList ( "one" ) ; oneEntryList.add( "two" ) ; // throws UnsupportedOperationException 2.  Arrays.asList() This returns a fixed-size list consisting of the number of elements provided as arguments. The number of elements provided would be an array hence the size is fixed to the length of the array. // Returns a fixed-size list List...

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...

Ubuntu DNS issue fix DNS_PROBE_FINISHED_BAD_CONFIG

Issue  I've been playing with a VPN and somehow it messed up my DNS resolution configurations. Chrome gives  DNS_PROBE_FINISHED_BAD_CONFIG  error and can't ping google. So it seemed to be an issue with the DNS. Of course, restarting didn't fix it. I tried DNS lookup which gave me below. To make sure this is somehting to do with my DNS confgis, I ran the same by providing the google DNS servers.  It works, which means my default DNS is not working for some reason. To make sure this, ran the below command. systemd-resolve --status Output has an entry for DNS Servers, which was  ::1 Fix 1. Edit the file /etc/systemd/resolved.conf. sudo vi /etc/systemd/resolved.conf 2. Add new DNS entries. I added 2 google DNS and the cloudflare DNS sever. [Resolve] DNS=8.8.8.8 8.8.4.4 1.1.1.1 3. Restart the systemd-resolved and check the configuration is persisted in /run/systemd/resolve/resolv.conf file. sudo service systemd-resolved restart cat /run/systemd/resolve/resolv.co...