Class RichTextComponent
- All Implemented Interfaces:
Animation, 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 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 ClassesModifier and TypeClassDescriptionstatic interfaceResolves an image source string (as it appears in the markup, e.g.static enumControls 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
ConstructorsConstructorDescriptionCreates an empty rich text component.RichTextComponent(String plainText) Creates a rich text component showing the given plain text. -
Method Summary
Modifier and TypeMethodDescriptionvoidAdds a listener notified when a hyperlink is tapped.Appends a run of text in the given style to the current content (builder style).Appends a run of styled text that acts as a hyperlink.protected DimensionCalculates the preferred size based on component content.protected DimensionMethod that can be overriden to represent the actual size of the component when it differs from the desireable size for the viewportclear()Removes all content, leaving the component empty.The current size mode.getText()The plain text of the current content (styling and structure removed).booleanIndicates whether the component should/could scroll on the Y axisvoidThis 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.voidpointerReleased(int x, int y) If this Component is focused, the pointer released event will call this methodpreferredSizeForWidth(int width) Lays the content out at the given outer width and returns the resulting preferred size (including this component's padding).voidRemoves a previously added link listener.setContent(String content, RichTextFormat format) Replaces the content parsed from the given format.Replaces the content with the given HTML fragment.Sets the resolver used to load inline images from their source strings.setLinkColor(int rgb) Sets the color (0xRRGGBB) used for hyperlink text that does not carry an explicit color.setMarkdown(String markdown) Replaces the content with the given Markdown source.Sets the sizing behavior.Replaces the content with unstyled plain text.setTextAlign(int align) Overrides the horizontal alignment of every paragraph, ignoring any alignment carried by the markup.voidsetWidth(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, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, addStylusListener, animate, announceForAccessibility, bindProperty, blocksSideSwipe, cancelRepaints, clearClientProperties, contains, containsOrOwns, createStyleAnimation, deinitialize, deinitializeCustomStyle, dragEnter, dragExit, dragFinished, draggingOver, dragInitiated, drawDraggedImage, drop, fireClicked, focusGained, focusLost, getAbsoluteX, getAbsoluteY, 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, 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, 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, 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, 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, remove, removeContextMenuListener, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removeMouseWheelListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, removeStylusListener, repaint, repaint, requestFocus, resetFocusable, respondsToPointerEvents, rotation, scrollRectToVisible, scrollRectToVisible, 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, 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, stripMarginAndPadding, styleChanged, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContains
-
Constructor Details
-
RichTextComponent
public RichTextComponent()Creates an empty rich text component. -
RichTextComponent
Creates a rich text component showing the given plain text.- Parameters:
plainText- the text
-
-
Method Details
-
setHtml
Replaces the content with the given HTML fragment.- Parameters:
html- the HTML markup- Returns:
- this, for chaining
-
setMarkdown
Replaces the content with the given Markdown source.- Parameters:
markdown- the Markdown source- Returns:
- this, for chaining
-
setContent
Replaces the content parsed from the given format.- Parameters:
content- the source contentformat- the format the content is written in- Returns:
- this, for chaining
-
setText
Replaces the content with unstyled plain text. Newlines become paragraph breaks.- Parameters:
plainText- the text- Returns:
- this, for chaining
-
clear
Removes all content, leaving the component empty. Useful before rebuilding content run by run withappend(String, TextStyle).- Returns:
- this, for chaining
-
append
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 textstyle- the run style, or null for the default style- Returns:
- this, for chaining
-
append
Appends a run of styled text that acts as a hyperlink.- Parameters:
runText- the run textstyle- the run style, or null for the default stylelink- the hyperlink target reported to link listeners, or null for none- Returns:
- this, for chaining
-
getText
The plain text of the current content (styling and structure removed).- Returns:
- the plain text
-
setTextAlign
Overrides the horizontal alignment of every paragraph, ignoring any alignment carried by the markup. Pass one ofComponent.LEFT,Component.CENTER,Component.RIGHT, or-1to restore per-paragraph alignment from the content.- Parameters:
align- the alignment constant, or -1 to clear the override- Returns:
- this, for chaining
-
preferredSizeForWidth
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
Sets the sizing behavior. Defaults toRichTextComponent.SizeMode.SHRINK.- Parameters:
mode- the size mode- Returns:
- this, for chaining
-
getSizeMode
-
isScrollableY
public boolean isScrollableY()Description copied from class:ComponentIndicates whether the component should/could scroll on the Y axis
Returns
whether the component is scrollable on the X axis
- Overrides:
isScrollableYin classComponent
-
setLinkColor
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
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
Adds a listener notified when a hyperlink is tapped. TheActionEvent.getSource()is the link target string.- Parameters:
l- the listener
-
removeLinkListener
Removes a previously added link listener.- Parameters:
l- the listener
-
setWidth
public void setWidth(int width) Description copied from class:ComponentSets 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
-
calcPreferredSize
Description copied from class:ComponentCalculates 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:
calcPreferredSizein classComponent
-
calcScrollSize
Description copied from class:ComponentMethod 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:
calcScrollSizein classComponent
-
paint
Description copied from class:ComponentThis 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
-
pointerReleased
public void pointerReleased(int x, int y) Description copied from class:ComponentIf this Component is focused, the pointer released event will call this method
Parameters
-
x: the pointer x coordinate -
y: the pointer y coordinate
- Overrides:
pointerReleasedin classComponent
-
-