Understanding JLabel in Java
Swing
A Guide to Displaying Text and
Images in GUI Applications
Introduction to JLabel
• - JLabel is a part of the javax.swing package.
• - Used to display a short string or an image
icon.
• - It is a non-editable component (read-only).
Features of JLabel
• - Displays:
• - Text
• - Icons
• - Both text and icons simultaneously.
• - Supports text alignment and positioning.
• - Allows HTML formatting for text.
JLabel Syntax
• JLabel label = new JLabel("Hello, JLabel!");
• Constructor Variants:
• - JLabel(String text)
• - JLabel(Icon image)
• - JLabel(String text, Icon image, int
horizontalAlignment)
Common Methods
• - setText(String text): Updates the displayed
text.
• - getText(): Retrieves the displayed text.
• - setIcon(Icon icon): Sets an image icon.
• - setHorizontalAlignment(int alignment):
Aligns content horizontally.
• - setVerticalAlignment(int alignment): Aligns
content vertically.
Example Code
• import javax.swing.*;
• public class JLabelExample {
• public static void main(String[] args) {
• JFrame frame = new JFrame("JLabel
Example");
• JLabel label = new JLabel("Welcome to
JLabel!", JLabel.CENTER);
• label.setIcon(new ImageIcon("icon.png"));
Properties and Customization
• - Background and foreground colors.
• - Font styling.
• - HTML-based styling for text:
• label.setText("<html><b>Bold</b> and
<i>Italic</i></html>");
Advantages of JLabel
• - Lightweight component.
• - Simplifies GUI development.
• - Supports advanced styling via HTML.
Limitations
• - Not interactive (cannot receive user input).
• - Used only for displaying content.
Conclusion
• - JLabel is a versatile component for displaying
text and images.
• - Plays an essential role in Java Swing GUI
development.
• - Simple to use yet highly customizable.