To simplify user interaction and make data entry easier, you can use java controls. Controls are components, such as buttons, labels and text boxes, that can be added to containers like frames, panels and applets. The Java.awt package provides an integrated set of classes to manage user interface components.
Labels are created via the Label class. Labels are often used to identify the purpose of other components on a given interface; they cannot be edited directly by the user. Using a label is much easier than using a drawString( ) method because labels are drawn automatically and don’t have to handled explicitly in the paint( ) method. Labels can be laid out according to the layout manager, instead of using [x, y] coordinates, as in drawString( ).
To create a Label, use one of the following constructors:
Label( ) - creates a label with its string aligned to the left..
Label(String) - creates a label initialized with the given string, and aligned left.
Label(String, int) - creates a label with specified text and alignment indicated by the int argument: Label.Right, Label.Left and Label.Center.
Example 3
The following is a simple applet that creates a few labels in Helvetica bold.
Public class LabelTest extends java.applet.Applet { Label left = new Label (“Left Wing”); Label center = new Label (“Central Part”, Label.CENTER); Label right = new Label (“Right Wing”, Label.RIGHT); Font f1 = new Font(“Helvetica”, Font.Bold, 14); GridLayout gd = new GridLayout(3,1);
Public void init(){ setFont(f1); setLayout(gd); add(left); add(center); add(right); } }
We can use label’s getText( ) method to indicate the current label’s text and setText( ) method to change the label’s text. We have also made use of setFont( ) method in the above example to change the label’s font and GridbagLayout to lay the components in the applet.