How to add an image in java

Sometimes we require adding images in the java projects so that they look cool. I have written this article, in which I will show you how to add an image to a project using JLabel.


Adding JLabel

Firstly, create a JFrame form file and add a JLabel to the JFrame.

Then select the JLabel and go to the properties window. There you will see an icon property, click the browse button.

JLabel

Importing an image to project

A new window will open, select the "External Image" option and then click the "Import to Project" button.

Importing

Then a new window will open. Here you have to select the image which you want to add to the project.

File Chooser


After selecting the image you will see that it is being included in the project and also in the JLabel. Resize the JLabel as required.

image in JLabel

This is how it looks when it runs.

JLabel image

Adding an image using code

Here I used ImageIcon class and also setIcon() function of JLabel class.

JLabel lbl = new JLabel();
ImageIcon img = new ImageIcon(PicURL);
lbl.setIcon(img);

Now you can add any number of images and make your projects cool. You can also use this image to set the background which I showed in my other post named "How to set a background image in java". Click here to learn about it.


The following two tabs change content below.
Amit Rawat

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