Ask Questions?

View Latest Questions


 
 

JLabel
Posted on: July 22, 2006 at 12:00 AM
Labels display fixed text or images on a GUI as information to the user.

Java: JLabel

 

Learn how to display fixed text or images with JLable component.

 

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

 

Here we are discussing about the 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>.

JLabel font and color

The most user-friendly interfaces are usually obtained by using the default appearance (font, color, background), but there are cases where you want to change these.

Appearance: setting the font

The font of a JLabel can be changed like this.

JLabel title = new JLabel("Want a Raise?", JLabel.CENTER);
title.setFont(new Font("Serif", Font.BOLD, 48));

Appearance: setting the text color

Use the setFor