Home » Java programming language

Java AWT Label

Java | AWT Label: In this tutorial, we will look at one of the Java AWT components, the AWT Label with example.
Submitted by Saranjay Kumar, on April 29, 2020

Label class is used to create labels that are generally limited to single-line messages (names, short notes, etc.). It is used to identify components. In GUI we need labels to identify the use of other components. For example, we need to specify the label for a button to indicate what action it performs on being clicked.

Labels do not support any interaction with the user and do not fire any events. So, there is no listener class for the labels. Users cannot change the text of a label. We can create a label by creating an instance of Label class.

Consider the following code -

import java.awt.*;
import javax.swing.*;

public class CreateLabel extends Frame{

        Label l1 = new Label("Label 1");
        Label l2 = new Label("Label 2", Label.CENTER);
         setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        public static void main(String []args){
        CreateLabel ob = new CreateLabel();


Java AWT Label

As seen in the code, we have created 2 Label objects, initialized in different ways. "l1" has been initialized with just a text. We can also create a blank label by not passing any parameter at the time of object creation. In "l2", we have passed a string as well as set the alignment of the label.

There are three types of alignment – left (left-justified), center (center justified), and right (right-justified). L1 is left justified, which is the default case. L2 has been centrally justified.

We have set the layout of the frame as BoxLayout (aligned along the y-axis). This places all the components one below the other. We will learn more about layouts in later sections.

The getAlignment() function is used to retrieve the present alignment of the label. As can be seen, 0 indicates that the label is left justified, 1 indicates center justified, and 2 indicates the right-justified.

We can also change the alignment of the label using the setAlignment(int) method of the Label class.

    void setAlignment(int alignment);

Just as in TextField and Button class, we have setText() and getText() methods to set and get the text of the label respectively.

    String getText();
    void setText(String text)

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.