Creating Labels in AWT using the Label class

The following example illustrates working with AWT Labels which are mostly used for demonstration purposes.

import java.awt.*;
class LabelDemo extends Frame
{
Label l1,l2;
    public LabelDemo()
    {
    setTitle("Label Demo");
    setLayout(new FlowLayout());
    setVisible(true);
   
    // Create labels
    l1=new Label("I am first label.");
    l2=new Label("I am second label.");
   
    // Add labels
    add(l1);
    add(l2);

    //pack the frame
    pack();
    }
    public static void main(String args[])
    {
    new LabelDemo();
    }
}

Notes: You can also create AWT Labels using the other constructors.
  • If you use the default constructor Label() then you can set the text by calling the setText(String text) method.
  • If you use the third constructor Label(String text, int alignment) then you can also set the alignment for the label. Possible alignments are Label.LEFT, Label.RIGHT, Label.CENTER
  • The second constructor as shown in the above example is mostly used. To align the label to a position you can call the setAlignment(int alignment) method.