ImageObserver
, MenuContainer
, Serializable
, Accessible
, SwingConstants
BasicComboBoxRenderer
, DefaultListCellRenderer
, DefaultTableCellRenderer
, DefaultTreeCellRenderer
@JavaBean(defaultProperty="UI", description="A component that displays a short string and an icon.") public class JLabel extends JComponent implements SwingConstants, Accessible
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 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: Swing is not thread safe. For more information see Swing's Threading Policy.
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 JavaBeans has been added to the java.beans
package. Please see XMLEncoder
.
Modifier and Type | Class | Description |
---|---|---|
protected class |
JLabel.AccessibleJLabel |
The class used to obtain the accessible role for this object. |
JComponent.AccessibleJComponent
Container.AccessibleAWTContainer
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
Modifier and Type | Field | Description |
---|---|---|
protected Component |
labelFor |
The Component this label is for; null if the label is not the label for a component |
listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
accessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
Constructor | Description |
---|---|
JLabel() |
Creates a JLabel instance with no image and with an empty string for the title. |
JLabel |
Creates a JLabel instance with the specified text. |
JLabel |
Creates a JLabel instance with the specified text and horizontal alignment. |
JLabel |
Creates a JLabel instance with the specified text, image, and horizontal alignment. |
JLabel |
Creates a JLabel instance with the specified image. |
JLabel |
Creates a JLabel instance with the specified image and horizontal alignment. |
Modifier and Type | Method | Description |
---|---|---|
protected int |
checkHorizontalKey |
Verify that key is a legal value for the horizontalAlignment properties. |
protected int |
checkVerticalKey |
Verify that key is a legal value for the verticalAlignment or verticalTextPosition properties. |
AccessibleContext |
getAccessibleContext() |
Get the AccessibleContext of this object |
Icon |
getDisabledIcon() |
Returns the icon used by the label when it's disabled. |
int |
getDisplayedMnemonic() |
Return the keycode that indicates a mnemonic key. |
int |
getDisplayedMnemonicIndex() |
Returns the character, as an index, that the look and feel should provide decoration for as representing the mnemonic character. |
int |
getHorizontalAlignment() |
Returns the alignment of the label's contents along the X axis. |
int |
getHorizontalTextPosition() |
Returns the horizontal position of the label's text, relative to its image. |
Icon |
getIcon() |
Returns the graphic image (glyph, icon) that the label displays. |
int |
getIconTextGap() |
Returns the amount of space between the text and the icon displayed in this label. |
Component |
getLabelFor() |
Get the component this is labelling. |
String |
getText() |
Returns the text string that the label displays. |
LabelUI |
getUI() |
Returns the L&F object that renders this component. |
String |
getUIClassID() |
Returns a string that specifies the name of the l&f class that renders this component. |
int |
getVerticalAlignment() |
Returns the alignment of the label's contents along the Y axis. |
int |
getVerticalTextPosition() |
Returns the vertical position of the label's text, relative to its image. |
boolean |
imageUpdate |
If the component is not showing or either the icon or disabled icon is not an ImageIcon with an Image equal to the passed in Image , return false ; otherwise it will delegate to the super-class. |
protected String |
paramString() |
Returns a string representation of this JLabel. |
void |
setDisabledIcon |
Set the icon to be displayed if this JLabel is "disabled" (JLabel.setEnabled(false)). |
void |
setDisplayedMnemonic |
Specifies the displayedMnemonic as a char value. |
void |
setDisplayedMnemonic |
Specify a keycode that indicates a mnemonic key. |
void |
setDisplayedMnemonicIndex |
Provides a hint to the look and feel as to which character in the text should be decorated to represent the mnemonic. |
void |
setHorizontalAlignment |
Sets the alignment of the label's contents along the X axis. |
void |
setHorizontalTextPosition |
Sets the horizontal position of the label's text, relative to its image. |
void |
setIcon |
Defines the icon this component will display. |
void |
setIconTextGap |
If both the icon and text properties are set, this property defines the space between them. |
void |
setLabelFor |
Set the component this is labelling. |
void |
setText |
Defines the single line of text this component will display. |
void |
setUI |
Sets the L&F object that renders this component. |
void |
setVerticalAlignment |
Sets the alignment of the label's contents along the Y axis. |
void |
setVerticalTextPosition |
Sets the vertical position of the label's text, relative to its image. |
void |
updateUI() |
Resets the UI property to a value from the current look and feel. |
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTree
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
protected Component labelFor
public JLabel(String text, Icon icon, int horizontalAlignment)
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.text
- The text to be displayed by the label.icon
- The image to be displayed by the label.horizontalAlignment
- One of the following constants defined in SwingConstants
: LEFT
, CENTER
, RIGHT
, LEADING
or TRAILING
.public JLabel(String text, int horizontalAlignment)
JLabel
instance with the specified text and horizontal alignment. The label is centered vertically in its display area.text
- The text to be displayed by the label.horizontalAlignment
- One of the following constants defined in SwingConstants
: LEFT
, CENTER
, RIGHT
, LEADING
or TRAILING
.public JLabel(String text)
JLabel
instance with the specified text. The label is aligned against the leading edge of its display area, and centered vertically.text
- The text to be displayed by the label.public JLabel(Icon image, int horizontalAlignment)
JLabel
instance with the specified image and horizontal alignment. The label is centered vertically in its display area.image
- The image to be displayed by the label.horizontalAlignment
- One of the following constants defined in SwingConstants
: LEFT
, CENTER
, RIGHT
, LEADING
or TRAILING
.public JLabel(Icon image)
JLabel
instance with the specified image. The label is centered vertically and horizontally in its display area.image
- The image to be displayed by the label.public JLabel()
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.public LabelUI getUI()
getUI
in class JComponent
@BeanProperty(hidden=true, visualUpdate=true, description="The UI object that implements the Component\'s LookAndFeel.") public void setUI(LabelUI ui)
ui
- the LabelUI L&F objectpublic void updateUI()
updateUI
in class JComponent
@BeanProperty(bound=false) public String getUIClassID()
getUIClassID
in class JComponent
public String getText()
@BeanProperty(preferred=true, visualUpdate=true, description="Defines the single line of text this component will display.") public void setText(String text)
The default value of this property is null.
This is a JavaBeans bound property.
text
- the single line of text this component will displaypublic Icon getIcon()
@BeanProperty(preferred=true, visualUpdate=true, description="The icon this component will display.") public void setIcon(Icon icon)
The default value of this property is null.
This is a JavaBeans bound property.
icon
- the default icon this component will displaypublic Icon getDisabledIcon()
Some look and feels might not render the disabled Icon, in which case they will ignore this.
disabledIcon
property@BeanProperty(visualUpdate=true, description="The icon to display if the label is disabled.") public void setDisabledIcon(Icon disabledIcon)
The default value of this property is null.
disabledIcon
- the Icon to display when the component is disabled@BeanProperty(visualUpdate=true, description="The mnemonic keycode.") public void setDisplayedMnemonic(int key)
key
- a keycode that indicates a mnemonic keypublic void setDisplayedMnemonic(char aChar)
aChar
- a char specifying the mnemonic to displaypublic int getDisplayedMnemonic()
@BeanProperty(visualUpdate=true, description="the index into the String to draw the keyboard character mnemonic at") public void setDisplayedMnemonicIndex(int index) throws IllegalArgumentException
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 setDisplayedMnemonic(KeyEvent.VK_A)
.
index
- Index into the String to underlineIllegalArgumentException
- will be thrown if index
is >= length of the text, or < -1public int getDisplayedMnemonicIndex()
protected int checkHorizontalKey(int key, String message)
key
- the property value to checkmessage
- the IllegalArgumentException detail messagekey
is a legal value for the horizontalAlignment propertiesIllegalArgumentException
- if key isn't LEFT, CENTER, RIGHT, LEADING or TRAILING.protected int checkVerticalKey(int key, String message)
key
- the property value to checkmessage
- the IllegalArgumentException detail messagekey
is a legal value for the verticalAlignment or verticalTextPosition propertiesIllegalArgumentException
- if key isn't TOP, CENTER, or BOTTOM.public int getIconTextGap()
@BeanProperty(visualUpdate=true, description="If both the icon and text properties are set, this property defines the space between them.") public void setIconTextGap(int iconTextGap)
The default value of this property is 4 pixels.
This is a JavaBeans bound property.
iconTextGap
- the space between the icon and text propertiespublic int getVerticalAlignment()
SwingConstants
: TOP
, CENTER
, or BOTTOM
.@BeanProperty(visualUpdate=true, enumerationValues={"SwingConstants.TOP","SwingConstants.CENTER","SwingConstants.BOTTOM"}, description="The alignment of the label\'s contents along the Y axis.") public void setVerticalAlignment(int alignment)
The default value of this property is CENTER.
alignment
- One of the following constants defined in SwingConstants
: TOP
, CENTER
(the default), or BOTTOM
.public int getHorizontalAlignment()
SwingConstants
: LEFT
, CENTER
, RIGHT
, LEADING
or TRAILING
.@BeanProperty(visualUpdate=true, enumerationValues={"SwingConstants.LEFT","SwingConstants.CENTER","SwingConstants.RIGHT","SwingConstants.LEADING","SwingConstants.TRAILING"}, description="The alignment of the label\'s content along the X axis.") public void setHorizontalAlignment(int alignment)
This is a JavaBeans bound property.
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
.public int getVerticalTextPosition()
SwingConstants
: TOP
, CENTER
, or BOTTOM
.@BeanProperty(expert=true, visualUpdate=true, enumerationValues={"SwingConstants.TOP","SwingConstants.CENTER","SwingConstants.BOTTOM"}, description="The vertical position of the text relative to it\'s image.") public void setVerticalTextPosition(int textPosition)
The default value of this property is CENTER.
This is a JavaBeans bound property.
textPosition
- One of the following constants defined in SwingConstants
: TOP
, CENTER
(the default), or BOTTOM
.public int getHorizontalTextPosition()
SwingConstants
: LEFT
, CENTER
, RIGHT
, LEADING
or TRAILING
.@BeanProperty(expert=true, visualUpdate=true, enumerationValues={"SwingConstants.LEFT","SwingConstants.CENTER","SwingConstants.RIGHT","SwingConstants.LEADING","SwingConstants.TRAILING"}, description="The horizontal position of the label\'s text, relative to its image.") public void setHorizontalTextPosition(int textPosition)
textPosition
- One of the following constants defined in SwingConstants
: LEFT
, CENTER
, RIGHT
, LEADING
, or TRAILING
(the default).public boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h)
ImageIcon
with an Image
equal to the passed in Image
, return false
; otherwise it will delegate to the super-class.imageUpdate
in interface ImageObserver
imageUpdate
in class Component
img
- the Image
to be comparedinfoflags
- flags used to repaint the label when the image is updated and which determine how much is to be paintedx
- the x coordinatey
- the y coordinatew
- the widthh
- the heightfalse
if the infoflags indicate that the image is completely loaded; true
otherwise.protected String paramString()
null
.paramString
in class JComponent
public Component getLabelFor()
@BeanProperty(description="The component this is labelling.") public void setLabelFor(Component c)
c
- the Component this label is for, or null if the label is not the label for a component@BeanProperty(bound=false, expert=true, description="The AccessibleContext associated with this Label.") public AccessibleContext getAccessibleContext()
getAccessibleContext
in interface Accessible
getAccessibleContext
in class Component
© 1993, 2023, Oracle and/or its affiliates. All rights reserved.
Documentation extracted from Debian's OpenJDK Development Kit package.
Licensed under the GNU General Public License, version 2, with the Classpath Exception.
Various third party code in OpenJDK is licensed under different licenses (see Debian package).
Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/swing/JLabel.html