Thursday, 14 May 2015

Labels in Java

Labels are text items that don't really do much. By using a label instead of drawString, you can use the Layout Managers to control text placement in a platform- and monitor-independent manner. The code in Listing 17.16 shows how to use labels. About the only significant flexibility you have, other than the alignment of the text, is the capability to change the font used

Listing 17.16. Using labels.
import java.awt.*;
import java.applet.Applet;


public class label_example extends Applet{
    Label the_labels[];

    public void init(){
        int i;
        //set up an array of labels
        the_labels = new Label[3];
        //Create a label with the default format
        the_labels[0] = new Label("on the left");
        //these two commands show how to set the color of a Label
        //the text itself is drawn with the Foreground color
        the_labels[0].setBackground(Color.red);
        the_labels[0].setForeground(Color.white);
        //Make a new Font and then assign it to the label
        Font a_font = new Font("TimesRoman",Font.PLAIN,24);
        the_labels[0].setFont(a_font);
        //Create a centered label
        the_labels[1] = new Label("middle", Label.CENTER);
        //Make a new Font and then assign it to the label
        a_font = new Font("TimesRoman",Font.BOLD,24);
        the_labels[1].setFont(a_font);
        //Create a label aligned to the right
        the_labels[2] = new Label("on the right", Label.RIGHT);
        //Make a new Font and then assign it to the label
        a_font = new Font("Helvetica",Font.ITALIC,18);
        the_labels[2].setFont(a_font);
        //these two commands show how to set the color of a Label
        //the text itself is drawn with the Foreground color
        the_labels[2].setBackground(Color.white);
        the_labels[2].setForeground(Color.blue);
        //add the three labels to the applet
        for(i=0;i<3;i++) {
            add(the_labels[i]);
        }
    }
}

The label creators and the most useful methods for the Label class follow:
new Label(String label)
Produces a label with the specified string.
new Label(String label,int positioning)
Produces a label with the string aligned according to the second value, which should be one of the three constants Label.CENTER, Label.LEFT, or Label.RIGHT.
String, getText()
Returns the label string.
setText(String new_label)

Changes the label text.  

No comments:

Post a Comment