# Class RichTextComponent

java.lang.Object
com.codename1.ui.Component
com.codename1.ui.RichTextComponent

All Implemented Interfaces:
  `Animation, Editable, StyleListener`

public class RichTextComponent extends Component

A read-only component that renders multi-styled, word-wrapped rich text: headings, bold / italic / underline / strike, inline code, colored and highlighted spans, per-paragraph alignment and indentation, ordered and unordered lists, block quotes, preformatted blocks, inline images and tappable hyperlinks. Content is supplied as HTML, Markdown, AsciiDoc, RTF or plain text, or built up programmatically from styled runs.

Unlike a single-style `Label`/`SpanLabel` it keeps a distinct style per character, and unlike a full `BrowserComponent` it is a lightweight native component that measures and paints text directly, so it embeds cleanly inside ordinary layouts and reports an accurate height-for-width preferred size. It is the read-only counterpart to the rich text editor: both share the same content model and `RichRunPainter` styling, so styled text rendered by one matches the other.

Typical use:

    RichTextComponent rt = new RichTextComponent();
    rt.setMarkdown("# Title\n\nSome **bold** and *italic* text with a [link](https://codenameone.com).");
    rt.addLinkListener(e -> CN.execute((String) e.getSource()));
    form.add(rt);

The default `RichTextComponent.SizeMode.SHRINK` makes the component as tall as its wrapped content at the width it is given (ideal inside a scrollable `Form`); `RichTextComponent.SizeMode.SCROLL` keeps the component at the size its parent assigns and scrolls its content vertically.

- ## Nested Class Summary

  Nested Classes
  Modifier and Type
  Class
  Description
  `static interface`
  `RichTextComponent.ImageResolver`
  Resolves an image source string (as it appears in the markup, e.g.
  `static enum`
  `RichTextComponent.SizeMode`
  Controls how the component sizes itself relative to its content.

- ## Field Summary

  ### Fields inherited from class Component

  `BASELINE, BOTTOM, BRB_CENTER_OFFSET, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_OTHER, CENTER, CROSSHAIR_CURSOR, DEFAULT_CURSOR, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_POSSIBLE_DRAG_Y, E_RESIZE_CURSOR, HAND_CURSOR, LEFT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NW_RESIZE_CURSOR, RIGHT, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, TOP, W_RESIZE_CURSOR, WAIT_CURSOR`

- ## Constructor Summary

  Constructors
  Constructor
  Description
  `RichTextComponent()`
  Creates an empty rich text component.
  `RichTextComponent(String plainText)`
  Creates a rich text component showing the given plain text.

- ## Method Summary

  Modifier and Type
  Method
  Description
  `void`
  `addLinkListener(ActionListener l)`
  Adds a listener notified when a hyperlink is tapped.
  `RichTextComponent`
  `append(String runText, TextStyle style)`
  Appends a run of text in the given style to the current content (builder style).
  `RichTextComponent`
  `append(String runText, TextStyle style, String link)`
  Appends a run of styled text that acts as a hyperlink.
  `protected Dimension`
  `calcPreferredSize()`
  Calculates the preferred size based on component content.
  `protected Dimension`
  `calcScrollSize()`
  Method that can be overriden to represent the actual size of the component when it differs from the desireable size for the viewport
  `RichTextComponent`
  `clear()`
  Removes all content, leaving the component empty.
  `RichTextComponent.SizeMode`
  `getSizeMode()`
  The current size mode.
  `String`
  `getText()`
  The plain text of the current content (styling and structure removed).
  `boolean`
  `isScrollableY()`
  Indicates whether the component should/could scroll on the Y axis
  `void`
  `paint(Graphics g)`
  This method paints the Component on the screen, it should be overriden by subclasses to perform custom drawing or invoke the UI API's to let the PLAF perform the rendering.
  `void`
  `pointerReleased(int x, int y)`
  If this Component is focused, the pointer released event will call this method
  `Dimension`
  `preferredSizeForWidth(int width)`
  Lays the content out at the given outer width and returns the resulting preferred size (including this component's padding).
  `void`
  `removeLinkListener(ActionListener l)`
  Removes a previously added link listener.
  `RichTextComponent`
  `setContent(String content, RichTextFormat format)`
  Replaces the content parsed from the given format.
  `RichTextComponent`
  `setHtml(String html)`
  Replaces the content with the given HTML fragment.
  `RichTextComponent`
  `setImageResolver(RichTextComponent.ImageResolver resolver)`
  Sets the resolver used to load inline images from their source strings.
  `RichTextComponent`
  `setLinkColor(int rgb)`
  Sets the color (0xRRGGBB) used for hyperlink text that does not carry an explicit color.
  `RichTextComponent`
  `setMarkdown(String markdown)`
  Replaces the content with the given Markdown source.
  `RichTextComponent`
  `setSizeMode(RichTextComponent.SizeMode mode)`
  Sets the sizing behavior.
  `RichTextComponent`
  `setText(String plainText)`
  Replaces the content with unstyled plain text.
  `RichTextComponent`
  `setTextAlign(int align)`
  Overrides the horizontal alignment of every paragraph, ignoring any alignment carried by the markup.
  `void`
  `setWidth(int width)`
  Sets the Component width, this method is exposed for the purpose of external layout managers and should not be invoked directly.

  ### Methods inherited from class Component

  `accessibilityChanged, accessibilityChanged, addContextMenuListener, addDragFinishedListener, addDragOverListener, addDropListener, addFocusListener, addLongPressListener, addMouseWheelListener, addNativeDragOverListener, addNativeDropListener, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, addStylusListener, animate, announceForAccessibility, bindProperty, blocksSideSwipe, canAcceptNativeDrop, cancelRepaints, clearClientProperties, consumesRawTextInput, contains, containsOrOwns, createNativeDragOperation, createStyleAnimation, deinitialize, deinitializeCustomStyle, deregisterFromAnimation, dragEnter, dragExit, dragFinished, draggingOver, dragInitiated, drawDraggedImage, drop, fireClicked, focusGained, focusLost, getAbsoluteX, getAbsoluteY, getAcceptedDropActions, getAcceptedDropMimeTypes, getAccessibilityNode, getAccessibilityText, getAllStyles, getAnimationManager, getBaseline, getBaselineResizeBehavior, getBindablePropertyNames, getBindablePropertyTypes, getBorder, getBottomGap, getBoundPropertyValue, getBounds, getBounds, getClientProperty, getCloudBoundProperty, getCloudDestinationProperty, getComponentForm, getComponentState, getCursor, getDefaultDragTransparency, getDirtyRegion, getDisabledStyle, getDraggedx, getDraggedy, getDragImage, getDragRegionStatus, getDragSpeed, getDragTransparency, getEditingDelegate, getGridPosX, getGridPosY, getHeight, getInlineAllStyles, getInlineDisabledStyles, getInlinePressedStyles, getInlineSelectedStyles, getInlineStylesTheme, getInlineUnselectedStyles, getInnerHeight, getInnerPreferredH, getInnerPreferredW, getInnerWidth, getInnerX, getInnerY, getLabelForComponent, getName, getNativeDragOperation, getNativeOverlay, getNextFocusDown, getNextFocusLeft, getNextFocusRight, getNextFocusUp, getOuterHeight, getOuterPreferredH, getOuterPreferredW, getOuterWidth, getOuterX, getOuterY, getOwner, getParent, getPreferredH, getPreferredSize, getPreferredSizeStr, getPreferredTabIndex, getPreferredW, getPressedStyle, getPropertyNames, getPropertyTypeNames, getPropertyTypes, getPropertyValue, getSameHeight, getSameWidth, getScrollable, getScrollAnimationSpeed, getScrollDimension, getScrollOpacity, getScrollOpacityChangeSpeed, getScrollX, getScrollY, getSelectCommandText, getSelectedRect, getSelectedStyle, getSemantics, getSideGap, getStyle, getTabIndex, getTensileLength, getTextSelectionSupport, getTooltip, getTopLevelContainer, getUIID, getUIManager, getUnselectedStyle, getVisibleBounds, getVisibleBounds, getWidth, getX, getY, growShrink, handlesInput, hasFixedPreferredSize, hasFocus, hideNativeOverlay, initComponent, initCustomStyle, initDisabledStyle, initLaf, initPressedStyle, initSelectedStyle, initUnselectedStyle, installDefaultPainter, isAlwaysTensile, isBlockLead, isCellRenderer, isChildOf, isDragActivated, isDragAndDropOperation, isDraggable, isDragRegion, isDropTarget, isEditable, isEditing, isEnabled, isFlatten, isFocusable, isGrabsPointerEvents, isHidden, isHidden, isHideInLandscape, isHideInPortrait, isHScrollThumbGrabbed, isHScrollThumbHover, isIgnorePointerEvents, isInClippingRegion, isInitialized, isNativeDragSource, isNativeDropTarget, isOpaque, isOwnedBy, isPinchBlocksDragAndDrop, isRippleEffect, isRTL, isScrollable, isScrollableX, isScrollVisible, isSelectableInteraction, isSetCursorSupported, isSmoothScrolling, isSnapToGrid, isStickyDrag, isTactileTouch, isTactileTouch, isTensileDragEnabled, isTraversable, isVisible, isVScrollThumbGrabbed, isVScrollThumbHover, keyPressed, keyReleased, keyRepeated, laidOut, longKeyPress, longPointerPress, mouseWheel, nativeDragEnter, nativeDragExit, nativeDragOver, nativeDrop, onScrollX, onScrollY, onSetFocusable, paintBackground, paintBackgrounds, paintBorder, paintBorderBackground, paintComponent, paintComponent, paintIntersectingComponentsAbove, paintLock, paintLockRelease, paintRippleOverlay, paintScrollbars, paintScrollbarX, paintScrollbarY, paintShadows, paramString, parsePreferredSize, pinch, pinch, pinchReleased, pointerDragged, pointerDragged, pointerHover, pointerHoverPressed, pointerHoverReleased, pointerPressed, pointerPressed, pointerReleased, putClientProperty, refreshTheme, refreshTheme, refreshTheme, registerForAnimation, remove, removeContextMenuListener, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removeMouseWheelListener, removeNativeDragOverListener, removeNativeDropListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, removeStylusListener, repaint, repaint, requestFocus, resetFocusable, respondsToPointerEvents, rotation, scrollRectToVisible, scrollRectToVisible, setAcceptedDropActions, setAcceptedDropMimeTypes, setAccessibilityText, setAlwaysTensile, setBlockLead, setBoundPropertyValue, setCellRenderer, setCloudBoundProperty, setCloudDestinationProperty, setComponentState, setCursor, setDefaultDragTransparency, setDirtyRegion, setDisabledStyle, setDraggable, setDragTransparency, setDropTarget, setEditingDelegate, setEnabled, setFlatten, setFocus, setFocusable, setGrabsPointerEvents, setHandlesInput, setHeight, setHidden, setHidden, setHideInLandscape, setHideInPortrait, setHorizontalScrollBounds, setIgnorePointerEvents, setInitialized, setInlineAllStyles, setInlineDisabledStyles, setInlinePressedStyles, setInlineSelectedStyles, setInlineStylesTheme, setInlineUnselectedStyles, setIsScrollVisible, setLabelForComponent, setName, setNativeDragOperation, setNativeDragSource, setNativeDropTarget, setNextFocusDown, setNextFocusLeft, setNextFocusRight, setNextFocusUp, setOpaque, setOwner, setPinchBlocksDragAndDrop, setPreferredH, setPreferredSize, setPreferredSizeStr, setPreferredTabIndex, setPreferredW, setPressedStyle, setPropertyValue, setPullToRefresh, setRippleEffect, setRTL, setSameHeight, setSameSize, setSameWidth, setScrollAnimationSpeed, setScrollOpacityChangeSpeed, setScrollSize, setScrollVisible, setScrollX, setScrollY, setSelectCommandText, setSelectedStyle, setShouldCalcPreferredSize, setSize, setSmoothScrolling, setSnapToGrid, setTabIndex, setTactileTouch, setTensileDragEnabled, setTensileLength, setTooltip, setTraversable, setUIID, setUIID, setUIIDFinal, setUnselectedStyle, setVerticalScrollBounds, setVisible, setX, setY, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, shouldRenderComponentSelection, showNativeOverlay, startEditingAsync, stopEditing, stopScrollMomentum, stripMarginAndPadding, styleChanged, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContains`

  ### Methods inherited from class Object

  `clone, equals, getClass, hashCode, notify, notifyAll, wait, wait, wait`

- ## Constructor Details

  - ### RichTextComponent

    public RichTextComponent()
    Creates an empty rich text component.

  - ### RichTextComponent

    public RichTextComponent(String plainText)
    Creates a rich text component showing the given plain text.
    Parameters:
      `plainText` - the text

- ## Method Details

  - ### setHtml

    public RichTextComponent setHtml(String html)
    Replaces the content with the given HTML fragment.
    Parameters:
      `html` - the HTML markup
    Returns:
      this, for chaining

  - ### setMarkdown

    public RichTextComponent setMarkdown(String markdown)
    Replaces the content with the given Markdown source.
    Parameters:
      `markdown` - the Markdown source
    Returns:
      this, for chaining

  - ### setContent

    public RichTextComponent setContent(String content, RichTextFormat format)
    Replaces the content parsed from the given format.
    Parameters:
      `content` - the source content
      `format` - the format the content is written in
    Returns:
      this, for chaining

  - ### setText

    public RichTextComponent setText(String plainText)
    Replaces the content with unstyled plain text. Newlines become paragraph breaks.
    Parameters:
      `plainText` - the text
    Returns:
      this, for chaining

  - ### clear

    public RichTextComponent clear()
    Removes all content, leaving the component empty. Useful before rebuilding content run by run with `append(String, TextStyle)`.
    Returns:
      this, for chaining

  - ### append

    public RichTextComponent append(String runText, TextStyle style)
    Appends a run of text in the given style to the current content (builder style). A run may contain newlines to start new paragraphs.
    Parameters:
      `runText` - the run text
      `style` - the run style, or null for the default style
    Returns:
      this, for chaining

  - ### append

    public RichTextComponent append(String runText, TextStyle style, String link)
    Appends a run of styled text that acts as a hyperlink.
    Parameters:
      `runText` - the run text
      `style` - the run style, or null for the default style
      `link` - the hyperlink target reported to link listeners, or null for none
    Returns:
      this, for chaining

  - ### getText

    public String getText()
    The plain text of the current content (styling and structure removed).
    Returns:
      the plain text

  - ### setTextAlign

    public RichTextComponent setTextAlign(int align)
    Overrides the horizontal alignment of every paragraph, ignoring any alignment carried by the markup. Pass one of `Component.LEFT`, `Component.CENTER`, `Component.RIGHT`, or `-1` to restore per-paragraph alignment from the content.
    Parameters:
      `align` - the alignment constant, or -1 to clear the override
    Returns:
      this, for chaining

  - ### preferredSizeForWidth

    public Dimension preferredSizeForWidth(int width)
    Lays the content out at the given outer width and returns the resulting preferred size (including this component's padding). This is a stateless height-for-width query useful for custom layout managers that need the wrapped size before assigning bounds.
    Parameters:
      `width` - the outer width available to the component
    Returns:
      the preferred size at that width

  - ### setSizeMode

    public RichTextComponent setSizeMode(RichTextComponent.SizeMode mode)
    Sets the sizing behavior. Defaults to `RichTextComponent.SizeMode.SHRINK`.
    Parameters:
      `mode` - the size mode
    Returns:
      this, for chaining

  - ### getSizeMode

    public RichTextComponent.SizeMode getSizeMode()
    The current size mode.
    Returns:
      the size mode

  - ### isScrollableY

    public boolean isScrollableY()
    Description copied from class: `Component`

    Indicates whether the component should/could scroll on the Y axis

    ###### Returns

    whether the component is scrollable on the X axis

    Overrides:
      `isScrollableY` in class `Component`

  - ### setLinkColor

    public RichTextComponent setLinkColor(int rgb)
    Sets the color (0xRRGGBB) used for hyperlink text that does not carry an explicit color.
    Parameters:
      `rgb` - the link color
    Returns:
      this, for chaining

  - ### setImageResolver

    public RichTextComponent setImageResolver(RichTextComponent.ImageResolver resolver)
    Sets the resolver used to load inline images from their source strings.
    Parameters:
      `resolver` - the image resolver, or null to render placeholders
    Returns:
      this, for chaining

  - ### addLinkListener

    public void addLinkListener(ActionListener l)
    Adds a listener notified when a hyperlink is tapped. The `ActionEvent.getSource()` is the link target string.
    Parameters:
      `l` - the listener

  - ### removeLinkListener

    public void removeLinkListener(ActionListener l)
    Removes a previously added link listener.
    Parameters:
      `l` - the listener

  - ### setWidth

    public void setWidth(int width)
    Description copied from class: `Component`

    Sets the Component width, this method is exposed for the purpose of external layout managers and should not be invoked directly.

    If a user wishes to affect the component size, setPreferredSize should be used.

    ###### Parameters

    - `width`: the width of the component

    ###### See also

    - #setPreferredSize
    Overrides:
      `setWidth` in class `Component`

  - ### calcPreferredSize

    protected Dimension calcPreferredSize()
    Description copied from class: `Component`

    Calculates the preferred size based on component content. This method is invoked lazily by getPreferred size.

    ###### Returns

    the calculated preferred size based on component content

    Overrides:
      `calcPreferredSize` in class `Component`

  - ### calcScrollSize

    protected Dimension calcScrollSize()
    Description copied from class: `Component`

    Method that can be overriden to represent the actual size of the component when it differs from the desireable size for the viewport

    ###### Returns

    scroll size, by default this is the same as the preferred size

    Overrides:
      `calcScrollSize` in class `Component`

  - ### paint

    public void paint(Graphics g)
    Description copied from class: `Component`

    This method paints the Component on the screen, it should be overriden by subclasses to perform custom drawing or invoke the UI API's to let the PLAF perform the rendering.

    ###### Parameters

    - `g`: the component graphics
    Specified by:
      `paint` in interface `Animation`
    Overrides:
      `paint` in class `Component`

  - ### pointerReleased

    public void pointerReleased(int x, int y)
    Description copied from class: `Component`

    If this Component is focused, the pointer released event will call this method

    ###### Parameters

    - `x`: the pointer x coordinate

    - `y`: the pointer y coordinate

    Overrides:
      `pointerReleased` in class `Component`