Java: JLabel

Labels display fixed text or images on a GUI as information to the user, for example, as a label in front of a a JTextField, etc. You can have text (including HTML), an image, or both on a JLabel. A JLabel has a transparent background, so it will always match the container it is in.

JLabel Constructors

Assume the following declarations.
   String text;
   Icon   image;
   int    alignment; // JLabel.LEFT, JLabel.Center, or JLabel.RIGHT.
   
JLabel yourLabel = new JLabel(text);
JLabel yourLabel = new JLabel(text, alignment);
JLabel yourLabel = new JLabel(image);
JLabel yourLabel = new JLabel(image, alignment);
JLabel yourLabel = new JLabel(text, image, alignment);

Java Idiom

Because there is usually no need to refer to a JLabel after it has been added to a container, it is common to combine creation and adding the JLabel in one statement. For example.
p.add(new JLabel("Enter your ID:", JLabel.RIGHT));
is the same as
JLabel idLabel = new JLabel("Enter your ID:", JLabel.RIGHT);
. . .
p.add(idLabel);

HTML in JLabels

You may put HTML text in a JLabel. In this case the text should begin with <html> and end with </html>.

Related pages

The most user-friendly interfaces are usually obtained by using the default appearance. Altho the default is the most common, you might want to change the font size in some situations. Look at JLabel font and color if you really must make changes. A more common way to control the appearance of a JLabel is using HTML (see above).

It's also possible to dynamically change the text of a JLabel, ie, use it for output. This is not generally a good idea because it may change the size of the JLabel and therefore require a change in the layout of components. Using a JTextField is much better. JLabel setting text has information for how to do it tho.