Class StyledLabel

  • All Implemented Interfaces:
    java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible, javax.swing.SwingConstants
    Direct Known Subclasses:
    ClickThroughStyledLabel, StyledListCellRenderer, StyledTreeCellRenderer

    public class StyledLabel
    extends javax.swing.JLabel
    StyledLabel is a special JLabel which can display text in different styles. It is a component between JLabel and JTextPane. JLabel is simple, fast but has limited features. For example, you can't use different color to draw the text. You may argue JLabel can use HTML tag to display text in different colors. However there are two main reasons to use StyledLabel. First of all, StyledLabel is very fast and almost as fast as JLabel with plain text. HTML JLabel is very slow. You can see StyledLabelPerformanceDemo.java in examples\B15. StyledLabel folder to see a performace test of HTML JLabel and StyledLabel. HTML JLabel is also buggy. See bug report at http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4373575. Sun claimed it is fixed but it is not as another user pointed it out at the end. If you run the test case provided by original submitter, you will immediately notice the tree node disappeared when you click on the tree nodes. This bug is actually one of the main reasons we decided to create StyledLabel. JTextPane is powerful and can display text in different color. But in the cases like cell renderer, JTextPane is obviously an overkill.

    StyledLabel sits between JLabel and JTextPane and provides a very simple and fast way to display text in different color and style. It can also support decorations using all kinds of line styles.

    All the methods on JLabel still work as before. The methods added in StyledLabel are several methods for StyleRange, such as addStyleRange(StyleRange), setStyleRanges(StyleRange[]), clearStyleRange(StyleRange), and clearStyleRanges().

    This is one thing about StyleRange that you should be aware of, which could be considered as a future enhancement item, is that the StyleRanges can't overlap with each other. For example, if you defined a StyleRange that covers from index 0 to index 3, you can't define any other StyleRange that overlaps with the first one. If you do so, the second StyleRange will be ignored.

    We borrowed some ideas from SWT's StyledText when we designed StyledLabel, especially StyleRange concept. Saying that, the features of the two components are not exactly the same since the purpose of the two components are quite different.

    See Also:
    Serialized Form
    • Nested Class Summary

      • Nested classes/interfaces inherited from class javax.swing.JLabel

        javax.swing.JLabel.AccessibleJLabel
      • Nested classes/interfaces inherited from class javax.swing.JComponent

        javax.swing.JComponent.AccessibleJComponent
      • Nested classes/interfaces inherited from class java.awt.Container

        java.awt.Container.AccessibleAWTContainer
      • Nested classes/interfaces inherited from class java.awt.Component

        java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy
    • Field Summary

      Fields 
      Modifier and Type Field Description
      static java.lang.String PROPERTY_IGNORE_COLOR_SETTINGS  
      static java.lang.String PROPERTY_STYLE_RANGE  
      • Fields inherited from class javax.swing.JLabel

        labelFor
      • Fields inherited from class javax.swing.JComponent

        listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
      • Fields inherited from class java.awt.Component

        accessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
      • Fields inherited from interface java.awt.image.ImageObserver

        ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
      • Fields inherited from interface javax.swing.SwingConstants

        BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
    • Constructor Summary

      Constructors 
      Constructor Description
      StyledLabel()  
      StyledLabel​(java.lang.String text)  
      StyledLabel​(java.lang.String text, int horizontalAlignment)  
      StyledLabel​(java.lang.String text, javax.swing.Icon icon, int horizontalAlignment)  
      StyledLabel​(javax.swing.Icon image)  
      StyledLabel​(javax.swing.Icon image, int horizontalAlignment)  
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void addStyleRange​(StyleRange styleRange)
      Adds a StyleRange into this StyledLabel.
      void addStyleRanges​(StyleRange[] styleRanges)
      Adds a list of StyleRanges into this StyledLabel.
      void clearStyleRange​(StyleRange styleRange)
      Removes the StyleRange.
      void clearStyleRanges()
      Clears all the StyleRanges.
      java.awt.Dimension getMaximumSize()  
      int getMaxRows()
      Gets the maximum rows possible after wrapping.
      java.awt.Dimension getMinimumSize()  
      int getMinRows()
      Gets the minimum rows possible after wrapping.
      int getPreferredWidth()
      Gets the preferred width of the styled label.
      int getRowGap()
      Gets the gap pixels between rows.
      int getRows()
      Gets the default row count to wrap the StyledLabel.
      StyleRange[] getStyleRanges()
      Gets the array of StyledText.
      java.lang.String getUIClassID()
      Returns a string that specifies the name of the L&F class that renders this component.
      boolean isIgnoreColorSettings()
      StyleRange could define color for the text and lines.
      boolean isLineWrap()
      Gets the flag indicating if the line should be automatically wrapped when the column width is limited.
      boolean isTruncated()
      Gets the status indicating if the StyledLabel is painted truncated.
      void setIgnoreColorSettings​(boolean ignoreColorSettings)
      Sets if the color defined by StyleRange should be ignored.
      void setLineWrap​(boolean lineWrap)
      Sets the flag indicating if the line should be automatically wrapped when the column width is limited.
      void setMaxRows​(int maxRows)
      Sets the maximum rows possible after wrapping.
      void setMinRows​(int minRows)
      Sets the minimum rows possible after wrapping.
      void setPreferredWidth​(int preferredWidth)
      Sets the preferred width of the styled label.
      void setRowGap​(int rowGap)
      Sets the gap pixels between rows.
      void setRows​(int rows)
      Sets the default row count to wrap the StyledLabel.
      void setStyleRanges​(StyleRange[] styleRanges)
      Clears all the old StyleRanges and adds a list of StyleRanges into this StyledLabel.
      void setTruncated​(boolean truncated)
      It will be invoked by BasicStyledLabelUI each time the StyledLabel is painted.
      void updateUI()
      Resets the UI property to a value from the current look and feel.
      • Methods inherited from class javax.swing.JLabel

        checkHorizontalKey, checkVerticalKey, getAccessibleContext, getDisabledIcon, getDisplayedMnemonic, getDisplayedMnemonicIndex, getHorizontalAlignment, getHorizontalTextPosition, getIcon, getIconTextGap, getLabelFor, getText, getUI, getVerticalAlignment, getVerticalTextPosition, imageUpdate, paramString, setDisabledIcon, setDisplayedMnemonic, setDisplayedMnemonic, setDisplayedMnemonicIndex, setHorizontalAlignment, setHorizontalTextPosition, setIcon, setIconTextGap, setLabelFor, setText, setUI, setVerticalAlignment, setVerticalTextPosition
      • Methods inherited from class javax.swing.JComponent

        addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, 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, 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
      • Methods inherited from class java.awt.Container

        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
      • Methods inherited from class java.awt.Component

        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, 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
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
    • Field Detail

      • PROPERTY_STYLE_RANGE

        public static final java.lang.String PROPERTY_STYLE_RANGE
        See Also:
        Constant Field Values
      • PROPERTY_IGNORE_COLOR_SETTINGS

        public static final java.lang.String PROPERTY_IGNORE_COLOR_SETTINGS
        See Also:
        Constant Field Values
    • Constructor Detail

      • StyledLabel

        public StyledLabel()
      • StyledLabel

        public StyledLabel​(javax.swing.Icon image)
      • StyledLabel

        public StyledLabel​(javax.swing.Icon image,
                           int horizontalAlignment)
      • StyledLabel

        public StyledLabel​(java.lang.String text)
      • StyledLabel

        public StyledLabel​(java.lang.String text,
                           int horizontalAlignment)
      • StyledLabel

        public StyledLabel​(java.lang.String text,
                           javax.swing.Icon icon,
                           int horizontalAlignment)
    • Method Detail

      • updateUI

        public void updateUI()
        Resets the UI property to a value from the current look and feel.
        Overrides:
        updateUI in class javax.swing.JLabel
        See Also:
        JComponent.updateUI()
      • getUIClassID

        public java.lang.String getUIClassID()
        Returns a string that specifies the name of the L&F class that renders this component.
        Overrides:
        getUIClassID in class javax.swing.JLabel
        Returns:
        the string "StyledLabelUI"
        See Also:
        JComponent.getUIClassID(), UIDefaults.getUI(javax.swing.JComponent)
      • addStyleRange

        public void addStyleRange​(StyleRange styleRange)
        Adds a StyleRange into this StyledLabel.
        Parameters:
        styleRange - the new StyleRange.
      • setStyleRanges

        public void setStyleRanges​(StyleRange[] styleRanges)
        Clears all the old StyleRanges and adds a list of StyleRanges into this StyledLabel.
        Parameters:
        styleRanges - set the StyleRanges.
      • addStyleRanges

        public void addStyleRanges​(StyleRange[] styleRanges)
        Adds a list of StyleRanges into this StyledLabel.
        Parameters:
        styleRanges - an array of StyleRanges.
      • getStyleRanges

        public StyleRange[] getStyleRanges()
        Gets the array of StyledText.
        Returns:
        the array of StyledText.
      • clearStyleRange

        public void clearStyleRange​(StyleRange styleRange)
        Removes the StyleRange.
        Parameters:
        styleRange - the StyleRange to be removed.
      • clearStyleRanges

        public void clearStyleRanges()
        Clears all the StyleRanges.
      • isIgnoreColorSettings

        public boolean isIgnoreColorSettings()
        StyleRange could define color for the text and lines. However when StyledLabel is used in cell renderer, the color could be conflict with selection color. So usually when it is used as cell renderer, the color defined in StyleRange should be ignored when cell is selected. If so, the foreground is used to paint all text and lines.
        Returns:
        true if the color defined by StyleRange should be ignored.
      • setIgnoreColorSettings

        public void setIgnoreColorSettings​(boolean ignoreColorSettings)
        Sets if the color defined by StyleRange should be ignored. This flag is used when StyledLabel is used as a selected cell renderer. Since the selection usually has it own unique selection background and foreground, the color setting set on this StyledLabel could be unreadable on the selection background, it'd better if we don't use any color settings in this case.
        Parameters:
        ignoreColorSettings - true or false.
      • getMinimumSize

        public java.awt.Dimension getMinimumSize()
        Overrides:
        getMinimumSize in class javax.swing.JComponent
      • getMaximumSize

        public java.awt.Dimension getMaximumSize()
        Overrides:
        getMaximumSize in class javax.swing.JComponent
      • setPreferredWidth

        public void setPreferredWidth​(int preferredWidth)
        Sets the preferred width of the styled label.
        Parameters:
        preferredWidth - the preferred width
        Since:
        3.2.0
      • getPreferredWidth

        public int getPreferredWidth()
        Gets the preferred width of the styled label.
        Returns:
        the preferred width
        Since:
        3.2.0
      • isLineWrap

        public boolean isLineWrap()
        Gets the flag indicating if the line should be automatically wrapped when the column width is limited.
        Returns:
        true if line wrap is needed. Otherwise false.
        Since:
        3.2.0
      • setLineWrap

        public void setLineWrap​(boolean lineWrap)
        Sets the flag indicating if the line should be automatically wrapped when the column width is limited.
        Parameters:
        lineWrap - the flag
        Since:
        3.2.0
      • getRows

        public int getRows()
        Gets the default row count to wrap the StyledLabel.
        Returns:
        the row count.
        Since:
        3.2.0
        See Also:
        setRows(int)
      • setRows

        public void setRows​(int rows)
        Sets the default row count to wrap the StyledLabel.

        By default, the value is 0. Any non-positive value is deemed as not configured.

        This has lower priority than setPreferredWidth(int). If preferred width is set, this flag does not take effect.

        Parameters:
        rows - the row count
        Since:
        3.2.0
      • getRowGap

        public int getRowGap()
        Gets the gap pixels between rows.
        Returns:
        the gap pixels.
        Since:
        3.2.0
        See Also:
        setRowGap(int)
      • setRowGap

        public void setRowGap​(int rowGap)
        Sets the gap pixels between rows.

        By default, the value is 0.

        Parameters:
        rowGap - the gap pixels.
      • getMaxRows

        public int getMaxRows()
        Gets the maximum rows possible after wrapping.
        Returns:
        the maximum rows.
        Since:
        3.2.0
      • setMaxRows

        public void setMaxRows​(int maxRows)
        Sets the maximum rows possible after wrapping.

        By default, the value is 0. Any non-positive value is deemed as not configured.

        Parameters:
        maxRows - the maximum rows
        Since:
        3.2.0
      • getMinRows

        public int getMinRows()
        Gets the minimum rows possible after wrapping.
        Returns:
        the minimum rows.
        Since:
        3.2.0
      • setMinRows

        public void setMinRows​(int minRows)
        Sets the minimum rows possible after wrapping.

        By default, the value is 0. Any non-positive value is deemed as not configured.

        Parameters:
        minRows - the minimum rows
        Since:
        3.2.0
      • isTruncated

        public boolean isTruncated()
        Gets the status indicating if the StyledLabel is painted truncated.
        Returns:
        true if its truncated. Otherwise false.
        Since:
        3.2.1
      • setTruncated

        public void setTruncated​(boolean truncated)
        It will be invoked by BasicStyledLabelUI each time the StyledLabel is painted. Please do NOT try to call this method to change the flag and NOT expect the setting could change the behavior of isTruncated().
        Parameters:
        truncated - the flag
        Since:
        3.2.1