public class RichTextComponent

  1. Object
  2. Component
  3. RichTextComponent

ImplementsAnimation, Editable, StyleListener

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 SizeMode.SHRINK makes the component as tall as its wrapped content at the width it is given (ideal inside a scrollable Form); SizeMode.SCROLL keeps the component at the size its parent assigns and scrolls its content vertically.

Nested types

enum RichTextComponent.SizeModeControls how the component sizes itself relative to its content.
interface RichTextComponent.ImageResolverResolves an image source string (as it appears in the markup, e.g. an <img src> URL or a Markdown image target) to a loaded Image.

Constructors

public RichTextComponent()Creates an empty rich text component.
public RichTextComponent(String plainText)Creates a rich text component showing the given plain text.

Methods

public RichTextComponent setHtml(String html)Replaces the content with the given HTML fragment.
public RichTextComponent setMarkdown(String markdown)Replaces the content with the given Markdown source.
public RichTextComponent setContent(String content, RichTextFormat format)Replaces the content parsed from the given format.
public RichTextComponent setText(String plainText)Replaces the content with unstyled plain text.
public RichTextComponent clear()Removes all content, leaving the component empty.
public RichTextComponent append(String runText, TextStyle style)Appends a run of text in the given style to the current content (builder style).
public RichTextComponent append(String runText, TextStyle style, String link)Appends a run of styled text that acts as a hyperlink.
public String getText()The plain text of the current content (styling and structure removed).
public RichTextComponent setTextAlign(int align)Overrides the horizontal alignment of every paragraph, ignoring any alignment carried by the markup.
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).
public RichTextComponent setSizeMode(RichTextComponent.SizeMode mode)Sets the sizing behavior.
public RichTextComponent.SizeMode getSizeMode()The current size mode.
public boolean isScrollableY()Indicates whether the component should/could scroll on the Y axis
public RichTextComponent setLinkColor(int rgb)Sets the color (0xRRGGBB) used for hyperlink text that does not carry an explicit color.
public RichTextComponent setImageResolver(RichTextComponent.ImageResolver resolver)Sets the resolver used to load inline images from their source strings.
public void addLinkListener(ActionListener l)Adds a listener notified when a hyperlink is tapped.
public void removeLinkListener(ActionListener l)Removes a previously added link listener.
public 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.
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
public 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.
public void pointerReleased(int x, int y)If this Component is focused, the pointer released event will call this method

Inherited fields

Inherited methods

From Component

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

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 String
the text

Method details

setHtml

public RichTextComponent setHtml(String html)
Replaces the content with the given HTML fragment.

Parameters

html String
the HTML markup

Returns

this, for chaining

setMarkdown

public RichTextComponent setMarkdown(String markdown)
Replaces the content with the given Markdown source.

Parameters

markdown String
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 String
the source content
format RichTextFormat
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 String
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 String
the run text
style TextStyle
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 String
the run text
style TextStyle
the run style, or null for the default style
link String
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 int
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 int
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 SizeMode.SHRINK.

Parameters

mode RichTextComponent.SizeMode
the size mode

Returns

this, for chaining

getSizeMode

public RichTextComponent.SizeMode getSizeMode()
The current size mode.

Returns

the size mode

isScrollableY

public boolean isScrollableY()
Indicates whether the component should/could scroll on the Y axis

Returns

whether the component is scrollable on the X axis

setLinkColor

public RichTextComponent setLinkColor(int rgb)
Sets the color (0xRRGGBB) used for hyperlink text that does not carry an explicit color.

Parameters

rgb int
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 RichTextComponent.ImageResolver
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 ActionListener
the listener

removeLinkListener

public void removeLinkListener(ActionListener l)
Removes a previously added link listener.

Parameters

l ActionListener
the listener

setWidth

public 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.

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

Parameters

width int
the width of the component

calcPreferredSize

protected Dimension calcPreferredSize()
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

calcScrollSize

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

Returns

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

paint

public 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.

Parameters

g Graphics
the component graphics

pointerReleased

public void pointerReleased(int x, int y)
If this Component is focused, the pointer released event will call this method

Parameters

x int
the pointer x coordinate
y int
the pointer y coordinate