FileDocCategorySizeDatePackage
JLabel.javaAPI DocJava SE 5 API52864Fri Aug 26 14:57:56 BST 2005javax.swing

JLabel

public class JLabel extends JComponent implements SwingConstants, Accessible
A display area for a short text string or an image, or both. A label does not react to input events. As a result, it cannot get the keyboard focus. A label can, however, display a keyboard alternative as a convenience for a nearby component that has a keyboard alternative but can't display it.

A JLabel object can display either text, an image, or both. You can specify where in the label's display area the label's contents are aligned by setting the vertical and horizontal alignment. By default, labels are vertically centered in their display area. Text-only labels are leading edge aligned, by default; image-only labels are horizontally centered, by default.

You can also specify the position of the text relative to the image. By default, text is on the trailing edge of the image, with the text and image vertically aligned.

A label's leading and trailing edge are determined from the value of its {@link java.awt.ComponentOrientation} property. At present, the default ComponentOrientation setting maps the leading edge to left and the trailing edge to right.

Finally, you can use the setIconTextGap method to specify how many pixels should appear between the text and the image. The default is 4 pixels.

See How to Use Labels in The Java Tutorial for further documentation.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see {@link java.beans.XMLEncoder}.

beaninfo
attribute: isContainer false description: A component that displays a short string and an icon.
version
1.116 04/02/04
author
Hans Muller

Fields Summary
private static final String
uiClassID
private int
mnemonic
private int
mnemonicIndex
private String
text
private Icon
defaultIcon
private Icon
disabledIcon
private boolean
disabledIconSet
private int
verticalAlignment
private int
horizontalAlignment
private int
verticalTextPosition
private int
horizontalTextPosition
private int
iconTextGap
protected Component
labelFor
static final String
LABELED_BY_PROPERTY
Client property key used to determine what label is labeling the component. This is generally not used by labels, but is instead used by components such as text areas that are being labeled by labels. When the labelFor property of a label is set, it will automatically set the LABELED_BY_PROPERTY of the component being labelled.
Constructors Summary
public JLabel(String text, Icon icon, int horizontalAlignment)
Creates a JLabel instance with the specified text, image, and horizontal alignment. The label is centered vertically in its display area. The text is on the trailing edge of the image.

param
text The text to be displayed by the label.
param
icon The image to be displayed by the label.
param
horizontalAlignment One of the following constants defined in SwingConstants: LEFT, CENTER, RIGHT, LEADING or TRAILING.


                                                                                                                                           
           
        setText(text);
        setIcon(icon);
        setHorizontalAlignment(horizontalAlignment);
        updateUI();
        setAlignmentX(LEFT_ALIGNMENT);
    
public JLabel(String text, int horizontalAlignment)
Creates a JLabel instance with the specified text and horizontal alignment. The label is centered vertically in its display area.

param
text The text to be displayed by the label.
param
horizontalAlignment One of the following constants defined in SwingConstants: LEFT, CENTER, RIGHT, LEADING or TRAILING.

        this(text, null, horizontalAlignment);
    
public JLabel(String text)
Creates a JLabel instance with the specified text. The label is aligned against the leading edge of its display area, and centered vertically.

param
text The text to be displayed by the label.

        this(text, null, LEADING);
    
public JLabel(Icon image, int horizontalAlignment)
Creates a JLabel instance with the specified image and horizontal alignment. The label is centered vertically in its display area.

param
image The image to be displayed by the label.
param
horizontalAlignment One of the following constants defined in SwingConstants: LEFT, CENTER, RIGHT, LEADING or TRAILING.

        this(null, image, horizontalAlignment);
    
public JLabel(Icon image)
Creates a JLabel instance with the specified image. The label is centered vertically and horizontally in its display area.

param
image The image to be displayed by the label.

        this(null, image, CENTER);
    
public JLabel()
Creates a JLabel instance with no image and with an empty string for the title. The label is centered vertically in its display area. The label's contents, once set, will be displayed on the leading edge of the label's display area.

        this("", null, LEADING);
    
Methods Summary
protected intcheckHorizontalKey(int key, java.lang.String message)
Verify that key is a legal value for the horizontalAlignment properties.

param
key the property value to check
param
message the IllegalArgumentException detail message
exception
IllegalArgumentException if key isn't LEFT, CENTER, RIGHT, LEADING or TRAILING.
see
#setHorizontalTextPosition
see
#setHorizontalAlignment

        if ((key == LEFT) ||
            (key == CENTER) ||
            (key == RIGHT) ||
            (key == LEADING) ||
            (key == TRAILING)) {
            return key;
        }
        else {
            throw new IllegalArgumentException(message);
        }
    
protected intcheckVerticalKey(int key, java.lang.String message)
Verify that key is a legal value for the verticalAlignment or verticalTextPosition properties.

param
key the property value to check
param
message the IllegalArgumentException detail message
exception
IllegalArgumentException if key isn't TOP, CENTER, or BOTTOM.
see
#setVerticalAlignment
see
#setVerticalTextPosition

        if ((key == TOP) || (key == CENTER) || (key == BOTTOM)) {
            return key;
        }
        else {
            throw new IllegalArgumentException(message);
        }
    
public javax.accessibility.AccessibleContextgetAccessibleContext()
Get the AccessibleContext of this object

return
the AccessibleContext of this object
beaninfo
expert: true description: The AccessibleContext associated with this Label.

        if (accessibleContext == null) {
            accessibleContext = new AccessibleJLabel();
        }
        return accessibleContext;
    
public javax.swing.IcongetDisabledIcon()
Returns the icon used by the label when it's disabled. If no disabled icon has been set this will forward the call to the look and feel to construct an appropriate disabled Icon.

Some look and feels might not render the disabled Icon, in which case they will ignore this.

return
the disabledIcon property
see
#setDisabledIcon
see
javax.swing.LookAndFeel#getDisabledIcon
see
ImageIcon

        if (!disabledIconSet && disabledIcon == null && defaultIcon != null) {
            disabledIcon = UIManager.getLookAndFeel().getDisabledIcon(this, defaultIcon);
            if (disabledIcon != null) {
                firePropertyChange("disabledIcon", null, disabledIcon);
            }
        }
        return disabledIcon;
    
public intgetDisplayedMnemonic()
Return the keycode that indicates a mnemonic key. This property is used when the label is part of a larger component. If the labelFor property of the label is not null, the label will call the requestFocus method of the component specified by the labelFor property when the mnemonic is activated.

return
int value for the mnemonic key
see
#getLabelFor
see
#setLabelFor

        return mnemonic;
    
public intgetDisplayedMnemonicIndex()
Returns the character, as an index, that the look and feel should provide decoration for as representing the mnemonic character.

since
1.4
return
index representing mnemonic character
see
#setDisplayedMnemonicIndex

        return mnemonicIndex;
    
public intgetHorizontalAlignment()
Returns the alignment of the label's contents along the X axis.

return
The value of the horizontalAlignment property, one of the following constants defined in SwingConstants: LEFT, CENTER, RIGHT, LEADING or TRAILING.
see
#setHorizontalAlignment
see
SwingConstants

        return horizontalAlignment;
    
public intgetHorizontalTextPosition()
Returns the horizontal position of the label's text, relative to its image.

return
One of the following constants defined in SwingConstants: LEFT, CENTER, RIGHT, LEADING or TRAILING.
see
SwingConstants

        return horizontalTextPosition;
    
public javax.swing.IcongetIcon()
Returns the graphic image (glyph, icon) that the label displays.

return
an Icon
see
#setIcon

        return defaultIcon;
    
public intgetIconTextGap()
Returns the amount of space between the text and the icon displayed in this label.

return
an int equal to the number of pixels between the text and the icon.
see
#setIconTextGap

        return iconTextGap;
    
public java.awt.ComponentgetLabelFor()
Get the component this is labelling.

return
the Component this is labelling. Can be null if this does not label a Component. If the displayedMnemonic property is set and the labelFor property is also set, the label will call the requestFocus method of the component specified by the labelFor property when the mnemonic is activated.
see
#getDisplayedMnemonic
see
#setDisplayedMnemonic

        return labelFor;
    
public java.lang.StringgetText()
Returns the text string that the label displays.

return
a String
see
#setText

        return text;
    
public javax.swing.plaf.LabelUIgetUI()
Returns the L&F object that renders this component.

return
LabelUI object

        return (LabelUI)ui;
    
public java.lang.StringgetUIClassID()
Returns a string that specifies the name of the l&f class that renders this component.

return
String "LabelUI"
see
JComponent#getUIClassID
see
UIDefaults#getUI

        return uiClassID;
    
public intgetVerticalAlignment()
Returns the alignment of the label's contents along the Y axis.

return
The value of the verticalAlignment property, one of the following constants defined in SwingConstants: TOP, CENTER, or BOTTOM.
see
SwingConstants
see
#setVerticalAlignment

        return verticalAlignment;
    
public intgetVerticalTextPosition()
Returns the vertical position of the label's text, relative to its image.

return
One of the following constants defined in SwingConstants: TOP, CENTER, or BOTTOM.
see
#setVerticalTextPosition
see
SwingConstants

        return verticalTextPosition;
    
public booleanimageUpdate(java.awt.Image img, int infoflags, int x, int y, int w, int h)
This is overridden to return false if the current Icon's Image is not equal to the passed in Image img.

see
java.awt.image.ImageObserver
see
java.awt.Component#imageUpdate(java.awt.Image, int, int, int, int, int)

        // Don't use getDisabledIcon, will trigger creation of icon if icon
        // not set.
	if (!isShowing() ||
            !SwingUtilities.doesIconReferenceImage(getIcon(), img) &&
            !SwingUtilities.doesIconReferenceImage(disabledIcon, img)) {

	    return false;
	}
	return super.imageUpdate(img, infoflags, x, y, w, h);
    
protected java.lang.StringparamString()
Returns a string representation of this JLabel. This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not be null.

return
a string representation of this JLabel.

	String textString = (text != null ?
			     text : "");
	String defaultIconString = ((defaultIcon != null) 
				    && (defaultIcon != this)  ?
				    defaultIcon.toString() : "");
	String disabledIconString = ((disabledIcon != null) 
				     && (disabledIcon != this) ?
				     disabledIcon.toString() : "");
	String labelForString = (labelFor  != null ?
				 labelFor.toString() : "");
        String verticalAlignmentString;
        if (verticalAlignment == TOP) {
            verticalAlignmentString = "TOP";
        } else if (verticalAlignment == CENTER) {
            verticalAlignmentString = "CENTER";
        } else if (verticalAlignment == BOTTOM) {
            verticalAlignmentString = "BOTTOM";
        } else verticalAlignmentString = "";
        String horizontalAlignmentString;
        if (horizontalAlignment == LEFT) {
            horizontalAlignmentString = "LEFT";
        } else if (horizontalAlignment == CENTER) {
            horizontalAlignmentString = "CENTER";
        } else if (horizontalAlignment == RIGHT) {
            horizontalAlignmentString = "RIGHT";
        } else if (horizontalAlignment == LEADING) {
            horizontalAlignmentString = "LEADING";
        } else if (horizontalAlignment == TRAILING) {
            horizontalAlignmentString = "TRAILING";
        } else horizontalAlignmentString = "";
        String verticalTextPositionString;
        if (verticalTextPosition == TOP) {
            verticalTextPositionString = "TOP";
        } else if (verticalTextPosition == CENTER) {
            verticalTextPositionString = "CENTER";
        } else if (verticalTextPosition == BOTTOM) {
            verticalTextPositionString = "BOTTOM";
        } else verticalTextPositionString = "";
        String horizontalTextPositionString;
        if (horizontalTextPosition == LEFT) {
            horizontalTextPositionString = "LEFT";
        } else if (horizontalTextPosition == CENTER) {
            horizontalTextPositionString = "CENTER";
        } else if (horizontalTextPosition == RIGHT) {
            horizontalTextPositionString = "RIGHT";
        } else if (horizontalTextPosition == LEADING) {
            horizontalTextPositionString = "LEADING";
        } else if (horizontalTextPosition == TRAILING) {
            horizontalTextPositionString = "TRAILING";
        } else horizontalTextPositionString = "";

	return super.paramString() +
	",defaultIcon=" + defaultIconString +
	",disabledIcon=" + disabledIconString +
	",horizontalAlignment=" + horizontalAlignmentString +
	",horizontalTextPosition=" + horizontalTextPositionString +
	",iconTextGap=" + iconTextGap +
	",labelFor=" + labelForString +
	",text=" + textString +
	",verticalAlignment=" + verticalAlignmentString +
	",verticalTextPosition=" + verticalTextPositionString;
    
public voidsetDisabledIcon(javax.swing.Icon disabledIcon)
Set the icon to be displayed if this JLabel is "disabled" (JLabel.setEnabled(false)).

The default value of this property is null.

param
disabledIcon the Icon to display when the component is disabled
see
#getDisabledIcon
see
#setEnabled
beaninfo
bound: true attribute: visualUpdate true description: The icon to display if the label is disabled.

        Icon oldValue = this.disabledIcon;
        this.disabledIcon = disabledIcon;
        disabledIconSet = (disabledIcon != null);
        firePropertyChange("disabledIcon", oldValue, disabledIcon);
        if (disabledIcon != oldValue) {
            if (disabledIcon == null || oldValue == null ||
                disabledIcon.getIconWidth() != oldValue.getIconWidth() ||
                disabledIcon.getIconHeight() != oldValue.getIconHeight()) {
                revalidate();
            } 
            if (!isEnabled()) {
                repaint();
            }
        }
    
public voidsetDisplayedMnemonic(int key)
Specify a keycode that indicates a mnemonic key. This property is used when the label is part of a larger component. If the labelFor property of the label is not null, the label will call the requestFocus method of the component specified by the labelFor property when the mnemonic is activated.

see
#getLabelFor
see
#setLabelFor
beaninfo
bound: true attribute: visualUpdate true description: The mnemonic keycode.

        int oldKey = mnemonic;
        mnemonic = key;
        firePropertyChange("displayedMnemonic", oldKey, mnemonic);

        setDisplayedMnemonicIndex(
            SwingUtilities.findDisplayedMnemonicIndex(getText(), mnemonic));

        if (key != oldKey) {
            revalidate();
            repaint();
        }
    
public voidsetDisplayedMnemonic(char aChar)
Specifies the displayedMnemonic as a char value.

param
aChar a char specifying the mnemonic to display
see
#setDisplayedMnemonic(int)

        int vk = (int) aChar;
        if(vk >= 'a" && vk <='z")
            vk -= ('a" - 'A");
        setDisplayedMnemonic(vk);
    
public voidsetDisplayedMnemonicIndex(int index)
Provides a hint to the look and feel as to which character in the text should be decorated to represent the mnemonic. Not all look and feels may support this. A value of -1 indicates either there is no mnemonic, the mnemonic character is not contained in the string, or the developer does not wish the mnemonic to be displayed.

The value of this is updated as the properties relating to the mnemonic change (such as the mnemonic itself, the text...). You should only ever have to call this if you do not wish the default character to be underlined. For example, if the text was 'Save As', with a mnemonic of 'a', and you wanted the 'A' to be decorated, as 'Save As', you would have to invoke setDisplayedMnemonicIndex(5) after invoking setMnemonic(KeyEvent.VK_A).

since
1.4
param
index Index into the String to underline
exception
IllegalArgumentException will be thrown if index= length of the text, or < -1
beaninfo
bound: true attribute: visualUpdate true description: the index into the String to draw the keyboard character mnemonic at

        int oldValue = mnemonicIndex;
        if (index == -1) {
            mnemonicIndex = -1;
        } else {
            String text = getText();
            int textLength = (text == null) ? 0 : text.length();
            if (index < -1 || index >= textLength) {  // index out of range
                throw new IllegalArgumentException("index == " + index);
            }
        }
        mnemonicIndex = index;
        firePropertyChange("displayedMnemonicIndex", oldValue, index);
        if (index != oldValue) {
            revalidate();
            repaint();
        }
    
public voidsetHorizontalAlignment(int alignment)
Sets the alignment of the label's contents along the X axis.

This is a JavaBeans bound property.

param
alignment One of the following constants defined in SwingConstants: LEFT, CENTER (the default for image-only labels), RIGHT, LEADING (the default for text-only labels) or TRAILING.
see
SwingConstants
see
#getHorizontalAlignment
beaninfo
bound: true enum: LEFT SwingConstants.LEFT CENTER SwingConstants.CENTER RIGHT SwingConstants.RIGHT LEADING SwingConstants.LEADING TRAILING SwingConstants.TRAILING attribute: visualUpdate true description: The alignment of the label's content along the X axis.

        if (alignment == horizontalAlignment) return;
        int oldValue = horizontalAlignment;
        horizontalAlignment = checkHorizontalKey(alignment,
                                                 "horizontalAlignment");
        firePropertyChange("horizontalAlignment",
                           oldValue, horizontalAlignment);
        repaint();
    
public voidsetHorizontalTextPosition(int textPosition)
Sets the horizontal position of the label's text, relative to its image.

param
textPosition One of the following constants defined in SwingConstants: LEFT, CENTER, RIGHT, LEADING, or TRAILING (the default).
exception
IllegalArgumentException
see
SwingConstants
beaninfo
expert: true bound: true enum: LEFT SwingConstants.LEFT CENTER SwingConstants.CENTER RIGHT SwingConstants.RIGHT LEADING SwingConstants.LEADING TRAILING SwingConstants.TRAILING attribute: visualUpdate true description: The horizontal position of the label's text, relative to its image.

        int old = horizontalTextPosition;
        this.horizontalTextPosition = checkHorizontalKey(textPosition,
                                                "horizontalTextPosition");
        firePropertyChange("horizontalTextPosition",
                           old, horizontalTextPosition);
        repaint();
    
public voidsetIcon(javax.swing.Icon icon)
Defines the icon this component will display. If the value of icon is null, nothing is displayed.

The default value of this property is null.

This is a JavaBeans bound property.

see
#setVerticalTextPosition
see
#setHorizontalTextPosition
see
#getIcon
beaninfo
preferred: true bound: true attribute: visualUpdate true description: The icon this component will display.

        Icon oldValue = defaultIcon;
        defaultIcon = icon;

        /* If the default icon has really changed and we had
         * generated the disabled icon for this component
         * (in other words, setDisabledIcon() was never called), then 
         * clear the disabledIcon field.
         */
        if ((defaultIcon != oldValue) && !disabledIconSet) {
            disabledIcon = null;
        }

        firePropertyChange("icon", oldValue, defaultIcon);

        if ((accessibleContext != null) && (oldValue != defaultIcon)) {
                accessibleContext.firePropertyChange(
                        AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY, 
                        oldValue, defaultIcon);
        }

        /* If the default icon has changed and the new one is 
         * a different size, then revalidate.   Repaint if the
         * default icon has changed.
         */
        if (defaultIcon != oldValue) {
            if ((defaultIcon == null) || 
                (oldValue == null) ||
                (defaultIcon.getIconWidth() != oldValue.getIconWidth()) ||
                (defaultIcon.getIconHeight() != oldValue.getIconHeight())) {
                revalidate();
            } 
            repaint();
        }
    
public voidsetIconTextGap(int iconTextGap)
If both the icon and text properties are set, this property defines the space between them.

The default value of this property is 4 pixels.

This is a JavaBeans bound property.

see
#getIconTextGap
beaninfo
bound: true attribute: visualUpdate true description: If both the icon and text properties are set, this property defines the space between them.

        int oldValue = this.iconTextGap;
        this.iconTextGap = iconTextGap;
        firePropertyChange("iconTextGap", oldValue, iconTextGap);
        if (iconTextGap != oldValue) {
            revalidate();
            repaint();
        }
    
public voidsetLabelFor(java.awt.Component c)
Set the component this is labelling. Can be null if this does not label a Component. If the displayedMnemonic property is set and the labelFor property is also set, the label will call the requestFocus method of the component specified by the labelFor property when the mnemonic is activated.

param
c the Component this label is for, or null if the label is not the label for a component
see
#getDisplayedMnemonic
see
#setDisplayedMnemonic
beaninfo
bound: true description: The component this is labelling.

        Component oldC = labelFor;
        labelFor = c;
        firePropertyChange("labelFor", oldC, c);        

        if (oldC instanceof JComponent) {
            ((JComponent)oldC).putClientProperty(LABELED_BY_PROPERTY, null);
        }
        if (c instanceof JComponent) {
            ((JComponent)c).putClientProperty(LABELED_BY_PROPERTY, this);
        }
    
public voidsetText(java.lang.String text)
Defines the single line of text this component will display. If the value of text is null or empty string, nothing is displayed.

The default value of this property is null.

This is a JavaBeans bound property.

see
#setVerticalTextPosition
see
#setHorizontalTextPosition
see
#setIcon
beaninfo
preferred: true bound: true attribute: visualUpdate true description: Defines the single line of text this component will display.


        String oldAccessibleName = null;
        if (accessibleContext != null) {
            oldAccessibleName = accessibleContext.getAccessibleName();
        }

        String oldValue = this.text;
        this.text = text;
        firePropertyChange("text", oldValue, text);

        setDisplayedMnemonicIndex(
                      SwingUtilities.findDisplayedMnemonicIndex(
                                          text, getDisplayedMnemonic()));

        if ((accessibleContext != null) 
            && (accessibleContext.getAccessibleName() != oldAccessibleName)) {
                accessibleContext.firePropertyChange(
                        AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY, 
                        oldAccessibleName,
                        accessibleContext.getAccessibleName());
        }
        if (text == null || oldValue == null || !text.equals(oldValue)) {
            revalidate();
            repaint();
        }
    
public voidsetUI(javax.swing.plaf.LabelUI ui)
Sets the L&F object that renders this component.

param
ui the LabelUI L&F object
see
UIDefaults#getUI
beaninfo
bound: true hidden: true attribute: visualUpdate true description: The UI object that implements the Component's LookAndFeel.

        super.setUI(ui);
        // disabled icon is generated by LF so it should be unset here
        if (!disabledIconSet && disabledIcon != null) {
            setDisabledIcon(null);
        }
    
public voidsetVerticalAlignment(int alignment)
Sets the alignment of the label's contents along the Y axis.

The default value of this property is CENTER.

param
alignment One of the following constants defined in SwingConstants: TOP, CENTER (the default), or BOTTOM.
see
SwingConstants
see
#getVerticalAlignment
beaninfo
bound: true enum: TOP SwingConstants.TOP CENTER SwingConstants.CENTER BOTTOM SwingConstants.BOTTOM attribute: visualUpdate true description: The alignment of the label's contents along the Y axis.

        if (alignment == verticalAlignment) return;
        int oldValue = verticalAlignment;
        verticalAlignment = checkVerticalKey(alignment, "verticalAlignment");
        firePropertyChange("verticalAlignment", oldValue, verticalAlignment); 
        repaint();
    
public voidsetVerticalTextPosition(int textPosition)
Sets the vertical position of the label's text, relative to its image.

The default value of this property is CENTER.

This is a JavaBeans bound property.

param
textPosition One of the following constants defined in SwingConstants: TOP, CENTER (the default), or BOTTOM.
see
SwingConstants
see
#getVerticalTextPosition
beaninfo
bound: true enum: TOP SwingConstants.TOP CENTER SwingConstants.CENTER BOTTOM SwingConstants.BOTTOM expert: true attribute: visualUpdate true description: The vertical position of the text relative to it's image.

        if (textPosition == verticalTextPosition) return;
        int old = verticalTextPosition;
        verticalTextPosition = checkVerticalKey(textPosition,
                                                "verticalTextPosition");
        firePropertyChange("verticalTextPosition", old, verticalTextPosition);
        repaint();
    
public voidupdateUI()
Resets the UI property to a value from the current look and feel.

see
JComponent#updateUI

        setUI((LabelUI)UIManager.getUI(this));
    
private voidwriteObject(java.io.ObjectOutputStream s)
See readObject() and writeObject() in JComponent for more information about serialization in Swing.

        s.defaultWriteObject();
        if (getUIClassID().equals(uiClassID)) {
            byte count = JComponent.getWriteObjCounter(this);
            JComponent.setWriteObjCounter(this, --count);
            if (count == 0 && ui != null) {
                ui.installUI(this);
            }
        }