- Details
- Written by Nam Ha Minh
- Last Updated on 06 July 2019   |   Print Email
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:- Creating a JLabel object
- Adding the label to a container
- Customizing JLabel’s appearance
- Labeling a component
- 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
- Change font style, background color and foreground color of the label:
label.setFont(new java.awt.Font("Arial", Font.ITALIC, 16));
label.setOpaque(true);
label.setBackground(Color.WHITE);
label.setForeground(Color.BLUE);
Image: NOTE:by default, the label’s background is transparent, so if you want to set background, you have to set the label’s opaque property to true. - Instead of using the methods above, we can use HTML code to customize the label’s appearance. For example:
label.setText("<html><font color=red size=4><b>WARNING!</b></html>");
Image: - We also must you HTML code if we want to add line breaks in the label’s text. For example:
JLabel label = new JLabel("<html><i>This label has <br>two lines</i><html>");
Image:
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:
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:
You can download the program’s source code in the attachment section.
Other Java Swing Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on
Facebook and watch
his Java videos you YouTube.