Java AWT Label Alignment

Java AWT Label Alignment

Label component displays text just like a drawString(). The difference is Label gets the status of a component so that it can be added in position format using layout manager. Label displays text in one line only. User cannot edit the text of the label. It is meant only for the programmer to display some information. The label does not raise any events (the other only component that does not raise events is Panel).

Just like with any other component, the label can be decorated with font and colors. The text of the label can be aligned with the following 3 symbolic constants defined in Label class.

public static final int LEFT = 0 label is aligned to left
public static final int CENTER = 1 label is aligned to center
public static final int RIGHT = 2 label is aligned to right

Following is the class signature

public class Label extends Component implements Accessible

Aligning the Label

Java AWT Label Alignment describes how to use labels with alignment and methods.

Java AWT Label Alignment

Java AWT Label Alignment

lab1 = new Label(“Center aligned text”, Label.CENTER);
lab2 = new Label(“Left aligned text”, Label.LEFT);

Three labels lab1, lab2 and lab3 are created. For lab1 and lab2, properties like text and alignment are set at the time of object creation itself through the constructor.

lab3 = new Label();
lab3.setText(“Right aligned text”);

The label lab3 is created with default constructor without any properties. They are set separately with setText() and setAlignment() methods. lab1 is given a font, a background color and a foreground color.

System.out.println(“lab1 text: ” + lab1.getText());
System.out.println(“lab1 alignment: ” + lab1.getAlignment());

With getText() method, the text of the label can be obtained and similarly with getAlignment() method, the alignment can be obtained (alignment is given in integer form).

Leave a Reply

Your email address will not be published. Required fields are marked *