How to Use Labels

 < Day Day Up > 

With the JLabel [77] class, you can display unselectable text and images. If you need to create a component that displays a string or an image (or both), you can do so by using or extending JLabel . If the component is interactive and has state, consider using a button instead of a label.

[77] JLabel API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JLabel.html.

By specifying HTML codes in a label's text, you can make the label have multiple lines, multiple fonts, multiple colors, and so on. If the label uses just a single color or font, you can avoid the overhead of HTML processing by using the setForeground or setFont method instead. See Using HTML in Swing Components (page 43) for details.

Figure 26 is a picture of an application that displays three labels. The window is divided into three rows of equal height; the label in each row is as wide as possible.

Figure 26. A screenshot of the LabelDemo , which displays three labels.

graphics/07fig26.gif

Try This:

  1. graphics/cd_icon.gif

    Run LabelDemo using Java Web Start or compile and run the example yourself. [78]

    [78] To run LabelDemo using Java Web Start, click the LabelDemo link on the RunExamples/components.html page on the CD. You can find the source files here: JavaTutorial/uiswing/components/example-1dot4/index.html#LabelDemo .

  2. Resize the window so you can see how the labels' contents are placed within the labels' drawing area. All the label contents have the default vertical alignmentthe label contents are centered vertically in the label's drawing area. The top label, which contains both image and text, is specified to have horizontal center alignment. The second label, which contains just text, has the left (leading) alignment that is the default for text-only labels in left-to-right languages. The third label, which contains just an image, has horizontal center alignment, which is the default for image-only labels.

Below is the code from LabelDemo.java that creates the labels in the previous example.

 ImageIcon icon = createImageIcon("images/middle.gif"); . . . label1 = new JLabel("Image and Text",                     icon,                     JLabel.CENTER); //Set the position of the text, relative to the icon: label1.setVerticalTextPosition(JLabel.BOTTOM); label1.setHorizontalTextPosition(JLabel.CENTER); label2 = new JLabel("Text-Only Label"); label3 = new JLabel(icon); 

The code for the createImageIcon method is similar to that used throughout this tutorial. You can find it explained in How to Use Icons (page 603) in Chapter 9.

Often, a label describes another component. When this is true, you can improve your program's accessibility by using the setLabelFor method to identify the component the label describes. For example:

 amountLabel.setLabelFor(amountField); 

The preceding code, taken from the FormattedTextFieldDemo example discussed in How to Use Formatted Text Fields (page 221), lets assistive technologies know that the label ( amountLabel ) provides information about the formatted text field ( amountField ). For more information about assistive technologies, see How to Support Assistive Technologies (page 519) in Chapter 9.

The Label API

Tables 38 through 40 list the commonly used JLabel constructors and methods. Other methods you're likely to call are defined by the Component and JComponent classes. They include setFont , setForeground , setBorder , setOpaque , and setBackground . See The JComponent Class (page 53) for details. You should also refer to the JLabel API documentation at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JLabel.html.

Note: In the following API, don't confuse label alignment with x and y alignment, which are used by layout managers and can affect the way any componentnot just a labelis sized or positioned. Label alignment, on the other hand, has no effect on a label's size or position. It simply determines where, inside the label's painting area, the label's contents are positioned. In the usual case, the label's painting area is exactly the size needed to paint the label, and thus label alignment is irrelevant. For more information about x and y alignment, see How to Use BoxLayout (page 462) in Chapter 8.


Table 38. Setting or Getting the Label's Contents

Method or Constructor

Purpose

 JLabel(Icon) JLabel(Icon, int) JLabel(String) JLabel(String, Icon, int) JLabel(String, int) JLabel() 

Create a JLabel instance, initializing it to have the specified text/image/alignment. The int argument specifies the horizontal alignment of the label's contents within its drawing area. The horizontal alignment must be one of the following constants defined in the SwingConstants interface (which JLabel implements): LEFT , CENTER , RIGHT , LEADING , or TRAILING . For ease of localization, we strongly encourage you to use LEADING and TRAILING , rather than LEFT and RIGHT .

 void setText(String) String getText() 

Set or get the text displayed by the label. You can use HTML tags to format the text, as described in Using HTML in Swing Components (page 43) in Chapter 3.

 void setIcon(Icon) Icon getIcon() 

Set or get the image displayed by the label.

 void setDisplayedMnemonic(char) char getDisplayedMnemonic() 

Set or get the letter that should look like a keyboard alternative. This is handy when a label describes a component (such as a text field) that has a keyboard alternative but can't display it. If the labelFor property is also set (using setLabelFor ), then when the user activates the mnemonic, the keyboard focus is transferred to the component specified by the labelFor property.

 void setDisplayedMnemonicIndex(int) int getDisplayedMnemonicIndex() 

Set or get a hint as to which character in the text should be decorated to represent the mnemonic. This is handy when you have two instances of the same character and wish to decorate the second instance. For example, setDisplayedMnemonicIndex(5) decorates the character that's at position 5 (that is, the 6th character in the text). Not all look and feels may support this feature. Introduced in 1.4.

 void setDisabledIcon(Icon) Icon getDisabledIcon() 

Set or get the image displayed by the label when it's disabled. If you don't specify a disabled image, then the look and feel creates one by manipulating the default image.

Table 39. Fine Tuning the Label's Appearance

Method

Purpose

 void setHorizontalAlignment(int) void setVerticalAlignment(int) int getHorizontalAlignment() int getVerticalAlignment() 

Set or get where in the label its contents should be placed. The SwingConstants interface defines five possible values for horizontal alignment: LEFT , CENTER (the default for image-only labels), RIGHT , LEADING (the default for text-only labels), TRAILING . For vertical alignment: TOP , CENTER (the default), and BOTTOM .

 void setHorizontalTextPosition(int) void setVerticalTextPosition(int) int getHorizontalTextPosition() int getVerticalTextPosition() 

Set or get where the button's text should be placed, relative to the button's image. The SwingConstants interface defines five possible values for horizontal position: LEADING , LEFT , CENTER , RIGHT , and TRAILING (the default). For vertical position: TOP , CENTER (the default), and BOTTOM .

 void setIconTextGap(int) int getIconTextGap() 

Set or get the number of pixels between the label's text and its image.

Table 40. Supporting Accessibility

Method

Purpose

 void setLabelFor(Component) Component getLabelFor() 

Set or get which component the label describes.

Examples That Use Labels

The following table lists some of the many examples that use labels.

Example

Where Described

Notes

LabelDemo

This section

Shows how to specify horizontal and vertical alignment, as well as aligning a label's text and image.

HtmlDemo

Using HTML in Swing Components (page 43)

Lets you experiment with specifying HTML text for a label.

AlignmentDemo

Providing Size and Alignment Hints (page 94)

Demonstrates a possible alignment problem when using a label in a vertical box layout. Shows how to solve the problem.

DialogDemo

How to Make Dialogs (page 187)

Uses a changeable label to display instructions and provide feedback.

SplitPaneDemo

How to Use Split Panes (page 369) and How to Use Lists (page 267)

Displays an image using a label inside of a scroll pane.

SliderDemo2

How to Use Sliders (page 348)

Uses JLabel to provide labels for a slider.

TableDialogEditDemo

How to Use Tables (page 388)

Implements a label subclass, ColorRenderer , to display colors in table cells .

FormattedTextFieldDemo

How to Use Formatted Text Fields (page 221)

Has four rows, each containing a label and the formatted text field it describes.

TextComponentDemo

Using Text Components (page 60)

TextComponentDemo has an inner class ( CaretListenerLabel ) that extends JLabel to provide a label that listens for events, updating itself based on the events.

ColorChooserDemo

How to Use Color Choosers (page 167)

Uses an opaque label to display the currently chosen color against a fixed-color background.

 < Day Day Up > 


JFC Swing Tutorial, The. A Guide to Constructing GUIs
The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
ISBN: 0201914670
EAN: 2147483647
Year: 2004
Pages: 171

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net