Using Components, the GUI Building Blocks |
The Label class provides an easy way of putting unselectable text in 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 Getting Information about a Font: FontMetrics.Labels are used throughout the examples in this tutorial. For example, in How to Use Choices, the example applet uses a label to display information about the item that's currently chosen.
Here's an applet that demonstrates label alignment:
The applet creates three labels, each one with a different alignment. If each label's display area were equal to the width of the text the label displayed, you wouldn't see any difference in the alignment of the labels. Each label's text would simply be displayed using all the available space. However, this applet makes each label's display area as wide as the applet, which is wider than any of the labels' text. As a result, you can see a difference in the horizontal position of the text drawn by the three labels. Here's the whole program.
Note: This applet's code requires no changes to compile cleanly in 1.1.
Below is the code that the applet uses to create its labels and set their alignment. For teaching purposes only, this applet uses all three Label constructors.
Besides the constructor,Label label1 = new Label(); label1.setText("Left"); Label label2 = new Label("Center"); label2.setAlignment(Label.CENTER); Label label3 = new Label("Right", Label.RIGHT);setText()
, andsetAlignment()
methods used above, the Label class also providesgetText()
andgetAlignment()
methods.
Using Components, the GUI Building Blocks |