Perhaps JLabelis the simplest Swing’s GUI component which simply renders a text message or an icon or both on screen. This article presents common practices when using JLabelin Swing development.

Table of content:

    1. Creating a JLabel object
    2. Adding the label to a container
    3. Customizing JLabel’s appearance
    4. Labeling a component
    5. JLabel demo program

 

1. Creating a JLabel object

JLabel label = new JLabel("Enter first name:", SwingConstants.RIGHT);

JLabel label = new JLabel(new ImageIcon("images/attention.jpg"),
							SwingConstants.LEFT);

 

2. Adding the label to a container

frame.add(label, BorderLayout.CENTER);
panel.add(label, gridbagConstraints);

 

3. Customizing JLabel’s appearance

JLabel label = new JLabel("<html><i>This label has <br>two lines</i><html>");


Image: label text has line breaks

 

4. Labeling a component

A JLabelis usually used for labeling a component such as a JTextField. If we want to allow the users accessing a text field using shortcut key (mnemonic), use the following code:

JTextField textEmail = new JTextField(20);

JLabel label = new JLabel("Enter e-mail address:");
label.setLabelFor(textEmail);
label.setDisplayedMnemonic('E');

 

Image: labeling a text field

You can notice that the ‘E’ letter in the label in underlined, so the users can type Alt + E to get focus on the text field.

 

5. JLabel demo program

For reference, we created a Swing program that demonstrates various techniques mentioned when working with JLabelcomponent. The program looks like this:

JLabel demo program

You can download the program’s source code in the attachment section.

 

Other Java Swing Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.

Attachments:
Download this file (SwingJLabelDemo.zip)SwingJLabelDemo.zip[Demo program for JLabel]12 kB