How to set background color of a JLabel

Many of you might be thinking that why I am writing a post on how to set the background color of the JLabel. But friends, just by changing the background property of the label you won't be able to do it.

Setting Background color of JLabel

Using IDE

So, let's first see this is done on NetBeans IDE using the JFrame Form file.

Firstly, drag a JLabel from the palette on to the JFrame. Then select the JLabel and go to the Properties window on the bottom right corner.

Background color

There you will see Background property then choose the desired color. But you will notice that the BG color of the label doesn't change.

Background color

Now keeping the label selected, go to the properties window scroll down and see for the opaque property and then check the checkbox. Now you will be able to see the change in the background color of the label.

Background color

Using code

Now let's achieve this by writing some code.

Firstly create a label using JLabel Class and then change the properties. Let's see how this is done.

JLabel label = new JLabel();

And you will get the same result as before.

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