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

How to Use Labels

The Label(in the API reference documentation) 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 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 Getting Information about a Font: FontMetrics(in the Creating a User Interface trail).

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:


Note: This applet's code requires no changes to compile cleanly in 1.1.
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.

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.

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 constructor, setText(), and setAlignment() methods used above, the Label class also provides getText() and getAlignment() methods.


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