Previous | Next | Trail Map | Creating a User Interface | Using Components, the GUI Building Blocks


How to Use Labels

The Label(in the API reference documentation)class provides an easy way of putting text in your program's GUI that the user can't edit or select. Labels are aligned to the left of their drawing area, by default. You can specify that they be centered or right-aligned by specifying Label.CENTER or Label.RIGHT either to the Label constructor or to the setAlignment() method. As with every Component, you can also specify the font and color of a Label. For information on working with fonts, see the bottom half of the page Working with Text(in the Creating a User Interface trail)[FIX: it should be on its own page].

Below are two applets that use labels.

LabelDemo:

Your browser doesn't under the <APPLET> tag. Here's what you would see if it did:


LabelAlignDemo:

Your browser doesn't under the <APPLET> tag. Here's what you would see if it did:


The first applet (LabelDemo) simply creates three labels with the default (left) alignment, puts them in a GridLayout, and then displays them. Here's the code for LabelDemo.

The second applet (LabelAlignDemo) does the same, except that it uses all three possible alignments. Because the applet is wider than necessary to display the text, and because GridLayout uses all available space, the Labels have a wider display area than they need. This results in a visible difference in the horizontal position of the three differently-aligned labels. Here's the code for LabelAlignDemo.

Below is the code that LabelAlignDemo uses to create its labels and set their alignment. For teaching purposes only, this applet uses all three Label constructors.

Label label1 = new Label();
label1.setText("Left");
Label label2 = new Label("Center");
label2.setAlignment(Label.CENTER);
Label label3 = new Label("Right", Label.RIGHT);
Besides the constructors, setText(), and setAlignment() methods used above, the Label class also provides getText() and getAlignment() methods.


Previous | Next | Trail Map | Creating a User Interface | Using Components, the GUI Building Blocks