Using Components, the GUI Building Blocks |
The Label class provides an easy way of putting uneditable, unselectable text into your program's GUI. 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 thesetAlignment()
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 [FIX: it should be on its own page].Below are two applets that use labels.
LabelDemo: LabelAlignDemo:
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 l1 = new Label(); l1.setText("Left"); Label l2 = new Label("Center"); l2.setAlignment(Label.CENTER); Label l3 = new Label("Right", Label.RIGHT);
Using Components, the GUI Building Blocks |