Labels are the simplest of all the AWT components. A label is a component that may contain uneditable text. They are generally limited to single-line messages (Labels, short notes, etc.). They are usually used to identify components. For example: In large GUI, it can be difficult to identify the purpose of every component unless the GUI designer provides labels (i.e. text information stating the purpose of each component).
Unlike any other component, labels do not support any interaction with the user and do not fire any events. So, there is no listener class for the labels .We can create label by creating an instance of Label class.The syntax for creating labels is as shown below:
Label label=new Label();
Label label=new Label(String str);
Label label=new Label(String str, int alignment);
The first form creates a blank label. The other two constructors create labels with the specified string; the third constructor specifies how text is aligned within the label. So, the second argument int.alignment will take the values LabeI.RIGHT, Label.LEFT and LabeI.CENTER, which are constants defined in the Label class. The string used in the label can be obtained using the method get Text(). To set a text for a label the method label.setText(“First Label”); is used.
The Label has no surrounding border that might indicate that it’s an editable text object. It also has virtually no use in user interaction. For example, you wouldn’t normally attempt to detect mouse clicks or other events over the Label.
AWT Label Interface
Method | Returns | Notes |
Label() Label(String label) | An empty label is somewhat unusual, but possible alignment is either Label.CENTER,Label. LEFT, or Label.RIGHT | |
Label(String label, int alignment) | ||
getAlignment() | Int | Returns LEFT, CENTER, or RIGHT |
getText | String | What’s on the Label right now? |
setAlignment (int alignment) | Void | Change the alignment of the existing text |
setText(String label) | Void | Paint a new text string in the same Label; this implies a layout manager relayout |
import java.awt.*;
class Labelframe extends Frame
{
Labelframe()
{
setLayout(new FlowLayout());
Label lblText = new Label("Lable Text");
Label lblTextAlign = new Label("RightAlignment",Label.RIGHT);
add(lblText);
add(lblTextAlign);
}
}
class LabelJavaAwt
{
public static void main(String args[])
{
Labelframe frame = new Labelframe();
frame.setTitle("Label Component");
frame.setSize(150,150);
frame.setVisible(true);
}
}