JLabel in Java Swing

The JLabel class is a Swing component for placing text in a container. It is used to display a single line of read-only text. The text can be changed by an application and can’t be edited by the user directly. It is a child class of JComponent class.

A display area for a short text string or an image, or both. A label does not react to input events. A JLabel object can display either text, an image, or both. You can specify where in the label’s display area the label’s contents are aligned by setting the vertical and horizontal alignment. By default, labels are vertically centered in their display area. Text-only labels are leading edge aligned, by default; image-only labels are horizontally centered, by default.

You can also specify the position of the text relative to the image. By default, the text is on the trailing edge of the image, with the text and image vertically aligned.

Constructors

JLabel()Creates a JLabel instance with no image and with an empty string for the title.
JLabel(Icon image)Creates a JLabel instance with the specified image.
JLabel(Icon image, int horizontalAlignment)Creates a JLabel instance with the specified image and horizontal alignment.
JLabel(String text)Creates a JLabel instance with the specified text.
JLabel(String text, Icon icon, int horizontalAlignment)Creates a JLabel instance with the specified text, image, and horizontal alignment.
JLabel(String text, int horizontalAlignment)Creates a JLabel instance with the specified text and horizontal alignment.

Example

public class JLabelDemo {
	public static void main(String[] args) {
		JFrame frame = new JFrame("JLabel Demo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(300, 300);
		frame.setVisible(true);
		frame.setLayout(null);
		// Adding Name label to frame
		JLabel name = new JLabel("Name:");
		name.setBounds(50, 100, 100, 20);
		frame.add(name);
		// Adding Value label to frame
		JLabel value = new JLabel("Coder Sathi");
		value.setBounds(100, 100, 100, 20);
		frame.add(value);
	}
}

Output

Java Swing JLabel

Conclusion

In this example, we learned how to create a JLabel and add it to JFrame.


Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments