Label Component
The Label component is the simplest of Java's AWT. Labels consist of a text string for display only and they never call an action method. The syntax is as follows:
Label labelname = new Label("This label is for decoration only.");
The justification of a label can be left, right, or centered. The line below will create a label that is right justified.
Label labelname = new Label("This label is for decoration only.",Label.RIGHT);
We can change the text of a label or get the label's text using the labelname.setText("This is new text."); or String labelText = labelname.getText(); methods. We can change the alignment or get the alignment of a label with the labelname.setAlignment(Label.CENTER); or int label Alignment = labelname.getAlignment(); methods.
The Applet below illustrates a simple label.
The code for the Applet is listed below
import java.applet.*;
import java.awt.*;
public class label extends Applet
{
public void init()
{
Label firstLabel = new Label("Labels
exist simply ");
add(firstLabel);
Label secLabel = new Label("to place
text on the screen");
add(secLabel);
Label thirdLabel = new Label("They
can be aligned left, right or center.");
add(thirdLabel);
}
}
|
We import all the facilities of the AWT
and applet that Java has to offer by using the * wildcard. We create an applet. Three labels are created and added to the applet window. |
The easiest way to obtain the code for this Applet is to click here and copy the contents of the screen that loads in your browser , paste it in a text editor and save it in a file called "label.java".
After compiling this program we need to create an HTML page with a reference to the class file. It will require a graphic window that is large enough to contain the labels (200 x 100 is a good size for this label).
Save the HTML code in the same directory as the class file.
When you load the HTML file in your browser the applet will execute as below.
View of the applet's output
Back to the Java AWT Components Page