Java AWT Label

The object of the Label class is a component for placing text in a container. It is used to display a single line of read only text. The text can be changed by a programmer but a user cannot edit it directly.

It is called a passive control as it does not create any event when it is accessed. To create a label, we need to create the object of Label class.

AWT Label Class Declaration

AWT Label Fields

The java.awt.Component class has following fields:

  1. static int LEFT: It specifies that the label should be left justified.
  2. static int RIGHT: It specifies that the label should be right justified.
  3. static int CENTER: It specifies that the label should be placed in center.

Label class Constructors

Sr. no.ConstructorDescription
1.Label()It constructs an empty label.
2.Label(String text)It constructs a label with the given string (left justified by default).
3.Label(String text, int alignement)It constructs a label with the specified string and the specified alignment.

Label Class Methods

Specified

Sr. no.Method nameDescription
1.void setText(String text)It sets the texts for label with the specified text.
2.void setAlignment(int alignment)It sets the alignment for label with the specified alignment.
3.String getText()It gets the text of the label
4.int getAlignment()It gets the current alignment of the label.
5.void addNotify()It creates the peer for the label.
6.AccessibleContext getAccessibleContext()It gets the Accessible Context associated with the label.
7.protected String paramString()It returns the string the state of the label.

Method inherited

The above methods are inherited by the following classes:

  • java.awt.Component
  • java.lang.Object

Java AWT Label Example

In the following example, we are creating two labels l1 and l2 using the Label(String text) constructor and adding them into the frame.

LabelExample.java

Output:

Java AWT Label

Java AWT Label Example with ActionListener

In the following example, we are creating the objects of TextField, Label and Button classes and adding them to the Frame. Using the actionPerformed() method an event is generated over the button. When we add the website in the text field and click on the button, we get the IP address of website.

LabelExample2.java

Output:

Java AWT Label




Latest Courses