5.2.1 Creating a GUI Component: The Label Class


The simplest GUI component is an object of type Label, which is just a single line of text that cannot be edited by the user, but only changed by the program itself.

The following example is an applet that consists of 2 labels. The Java code has been kept is small as possible.

The Applet
The Java Code
import java.applet.Applet;
import java.awt.*;

public class PersonalData extends Applet {

  public void init() {
    add( new Label("Surname,") );
    add( new Label("Initials", Label.RIGHT) );
  }
}
The example shows two constructors of a Label object: To change the text and alignment of the text of an existing you can use the methods setText and setAlignment. So, instead of the single line
   new Label("Initials", Label.RIGHT));
you could have used the following lines of Java code:
   Label initials = new Label();         // create an empty label
   initials.setText("initials");        // set the text of the label
   initials.setAlignment(Label.RIGHT);  // align the text in the label

The following table lists the constructors and methods for labels.

Constructors Meaning
Label() creates an empty label
Label(String label) creates a label with given text string
Label(String label, int alignment) creates a label with given text string and alignment; available alignments are Label.LEFT (0), Label.CENTER (1), and Label.RIGHT (2)
Methods Meaning
getAlignment() returns the alignment of the text string of the label
getText() returns the text string of the label
setAlignment(int alignment) changes the alignment of the text string of the label
setText(String label) changes the text string of the label

Since the Label class is a subclass of Component, it inherits a lot of behavior from this parent class. In particular, a label has a foreground color, a background color, and a font. You can set these properties by calling methods defined in the Component class. In the following applet the labels are more colorful.
The Applet
The Java Code
import java.applet.Applet;
import java.awt.*;

public class PersonalData extends Applet {

  Label surname, initials;
 
  public void init() {
    //  create labels
    surname = new Label("Surname,");
    initials = new Label("Initials", Label.RIGHT);
    //  change color and font of labels
    surname.setForeground(Color.red);
    surname.setBackground(Color.black);
    surname.setFont(new Font("TimesRoman", Font.BOLD, 18));
    initials.setForeground(Color.green);
    initials.setBackground(Color.blue);
    //  add labels to panel
    add(surname);
    add(initials);
  }
}

In the above example, after the labels have been created and properties have been set, they are placed in the applet via the add method of the Container class. As you will see, every GUI component is added in this way to a container.