Working with Label by Using JLabel Class

In this tutorial, we will show you how to use JLabel class to create various kinds of labels in Swing including simple label, icon label, and HTML label.

The label is the simplest component in the Swing toolkit. The label can contain text, icon or both. To create a simple and non-interactive label, you use JLabel class.

Here are the common constructors of JLabel class:

JLabel ConstructorsMeaning
public JLabel() Creates a label with no icon or text.
public JLabel(Icon image)Creates a label with a given icon.
public JLabel(Icon image, int horizontalAlignment)Creates a label with a given icon and horizontal alignment.
public JLabel(String text)Creates a label with a given text.
public JLabel(String text, Icon icon, int horizontalAlignment)Creates a label with a given text, icon, and horizontal alignment.
public JLabel(String text, int horizontalAlignment)Creates a label with a given text and horizontal alignment.

Example of creating a simple label with JLabel

In this example, we create a very simple label with simple text. Here is the output of the demo application:

JLabel Demo

Example of creating a label with image

To create a label with a given image, first, you create an instance of ImageIcon by providing the image path. And then you create the label based on the ImageIcon instance.

Here is the output of the demo application:

JLabel with Image

Example of creating a label with HTML text

JLabel also supports the HTML text beside the simple text and icon. To create a label with HTML text, you just need to pass the HTML fragment into JLabel constructor. The HTML fragment has to start with <html> in order to allow Swing to render it as HTML.

Here is the output of the demo application:

JLabel with HTML Text

  • Was this tutorial helpful ?
  • YesNo