Class JTextPane
- All Implemented Interfaces:
ImageObserver, MenuContainer, Serializable, Accessible, Scrollable
Emulator for
Unlike
JTextPane — a thin subclass of JEditorPane
over the same SJEditorPane (RTE) peer, backed by a
DefaultStyledDocument whose styled runs render through RTE's HTML
value (D_jtextpane).
JTextPane pane = new JTextPane();
StyledDocument doc = pane.getStyledDocument();
SimpleAttributeSet red = new SimpleAttributeSet();
StyleConstants.setForeground(red, Color.RED);
StyleConstants.setBold(red, true);
doc.insertString(0, "alert", red); // renders bold red in the browser
What renders (the RTE subset)
Bold, italic, underline, strike-through, foreground/background colour, super/subscript, paragraph alignment, andImageIcon embedding all map to
HTML and render. Anything RTE can't represent (font family/size, indents, line
spacing, insertComponent, a non-ImageIcon icon) WARNs per call
and is dropped — see RteHtmlCodec.
getText() is plain text
Unlike JEditorPane (whose getText() is HTML), a JTextPane's
document holds the visible text with styling carried on run attributes,
so getText() returns plain text — matching real JTextPane. A
consequence: setText("<b>hi</b>") shows the literal string, as a
plain-StyledEditorKit JTextPane would, not bold.
Two-way sync
ADocumentListener serializes the document → RTE-subset HTML and
pushes it through the peer's main value on every mutation (so
doc.insertString/setCharacterAttributes render). Browser edits
fire the peer's value-change; the reverse reads that same HTML value back
(getValue()) and rebuilds the document (clear + re-insert) so
getText()/getStyledDocument() reflect them and user
DocumentListeners fire (R_swing_is_truth/R_callswing_envelope). preventPeerEvents guards the loop.
One value format both ways: reading getValue() — the property the change
event fired on — avoids the cross-property staleness of reading asDelta()
(a different property that can lag the htmlValue edit), and push stays HTML
because asDelta().setValue's async htmlValue reconcile races Quill
to empty during construction — see RteHtmlCodec.toHtml(StyledDocument).
Selection-based styled methods
The selection-basedsetCharacterAttributes(AttributeSet, boolean)/getCharacterAttributes()
operate on the pane's input attributes whatever the caret selects (the
JDK's no-selection behaviour); programmatic
styling that actually renders goes through the offset-based
getStyledDocument().setCharacterAttributes(offset, len, …) path.
R_leaf_peer_lockdown: leaf lock-down
No publicjavax.swing.* class extends JTextPane, so it is a leaf: it omits
the protected (Component peer) ctor and hard-codes new SJEditorPane()
through JEditorPane's protected D_peer_ctor_injection seam. Non-final so behaviour-subclassing
still works.- See Also:
-
Field Summary
Fields inherited from class JEditorPane
HONOR_DISPLAY_PROPERTIES, W3C_LENGTH_UNITSFields inherited from class JTextComponent
DEFAULT_KEYMAP, FOCUS_ACCELERATOR_KEY, preventPeerEventsFields inherited from class JComponent
TOOL_TIP_TEXT_KEY, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOWFields inherited from class Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, FILL_CHROME, FILL_DEFAULT, LEFT_ALIGNMENT, listenerList, RIGHT_ALIGNMENT, TOP_ALIGNMENTFields inherited from interface ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH -
Constructor Summary
ConstructorsConstructorDescriptionJTextPane(StyledDocument doc) Installsdocas the model (must be aStyledDocument). -
Method Summary
Modifier and TypeMethodDescriptionprotected DocumentFactory for the defaultDocument.protected EditorKitThe pending-input character attributes (JDK returns these at an empty selection).Logical style of the first paragraph.Paragraph attributes of the first paragraph (JDK reads these at the caret).protected final StyledEditorKitvoidDrop-and-WARN: a live inline component has no Delta/RTE representation.voidinsertIcon(Icon g) Embeds an image: anImageIconrasterises to a base64 PNG Delta image op and renders as<img>.protected voidPushessetText's markup into RTE'shtmlValueunderpreventPeerEvents(so the peer's value-change listener doesn't re-mirror our own write back into the Document).voidremoveStyle(String nm) voidsetCharacterAttributes(AttributeSet attr, boolean replace) Appliesattrto the pane's input attributes whatever is selected, which makes no visible change: the JDK's no-selection behaviour, where the JDK would style a selection.voidsetDocument(Document doc) final voidsetEditorKit(EditorKit kit) Install an editor kit.voidSets the logical style of the first paragraph (JDK applies it at the caret).voidsetParagraphAttributes(AttributeSet attr, boolean replace) Applies paragraphattrto the first paragraph — the JDK's behaviour at an empty selection (setParagraphAttributes(0, 0, …)), which does render (e.g. alignment).voidConvenience forsetDocument(Document)typed toStyledDocument.protected voidwirePeerToDocument(com.vaadin.swingbridge.surrogates.SJEditorPane editor) Subscribes to browser edits and mirrors them into the Document (EAGER per R_swing_is_truth's "tracks typing",callSwingper R_callswing_envelope).Methods inherited from class JEditorPane
addHyperlinkListener, createEditorKitForContentType, fireHyperlinkUpdate, getContentType, getEditorKit, getEditorKitForContentType, getHyperlinkListeners, getPage, getStream, getText, removeHyperlinkListener, scrollToReference, setContentType, setEditable, setEditorKitForContentType, setPage, setPage, setTextMethods inherited from class JTextComponent
addCaretListener, addKeymap, copy, cut, fireCaretUpdate, getAccessibleContext, getActions, getCaret, getCaretColor, getCaretListeners, getCaretPosition, getDisabledTextColor, getDocument, getDragEnabled, getDropMode, getFocusAccelerator, getHighlighter, getInputMethodRequests, getKeymap, getKeymap, getMargin, getNavigationFilter, getPreferredScrollableViewportSize, getPrintable, getScrollableBlockIncrement, getScrollableTracksViewportHeight, getScrollableTracksViewportWidth, getScrollableUnitIncrement, getSelectedText, getSelectedTextColor, getSelectionColor, getSelectionEnd, getSelectionStart, getText, getToolTipText, getUI, isEditable, modelToView, modelToView2D, moveCaretPosition, paramString, paste, print, print, print, read, removeCaretListener, removeKeymap, removeNotify, replaceSelection, restoreComposedText, saveComposedText, select, selectAll, setCaret, setCaretColor, setCaretPosition, setComponentOrientation, setDisabledTextColor, setDragEnabled, setDropMode, setFocusAccelerator, setHighlighter, setKeymap, setMargin, setNavigationFilter, setSelectedTextColor, setSelectionColor, setSelectionEnd, setSelectionStart, setUI, updateUI, viewToModel, viewToModel2D, writeMethods inherited from class JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, 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, 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, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, 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, updateMethods inherited from class Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, addSlotChild, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, fireHierarchyEvent, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, peerContentElement, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, removeSlotChild, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTreeMethods inherited from class Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, applyBackgroundToPeer, applyVisibleToPeer, awtListeners, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, defaultFillCssClass, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, fireComponentEvent, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isThemeDefault, 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, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, suppressMouseBridge, toString, transferFocus, transferFocusBackward, transferFocusUpCycle, withPeer, withPeerOnLiveUI
-
Constructor Details
-
JTextPane
public JTextPane() -
JTextPane
Installsdocas the model (must be aStyledDocument).
-
-
Method Details
-
createDefaultDocument
Description copied from class:JTextComponentFactory for the defaultDocument. Real Swing subclasses override to pick richer Document models (the EditorKit-driven path in JEditorPane, etc.). Our base picksPlainDocument— the simplest line- oriented model, and what JTextField would pick anyway.- Overrides:
createDefaultDocumentin classJEditorPane
-
getStyledDocument
-
setStyledDocument
Convenience forsetDocument(Document)typed toStyledDocument. -
setDocument
- Overrides:
setDocumentin classJTextComponent
-
wirePeerToDocument
protected void wirePeerToDocument(com.vaadin.swingbridge.surrogates.SJEditorPane editor) Description copied from class:JEditorPaneSubscribes to browser edits and mirrors them into the Document (EAGER per R_swing_is_truth's "tracks typing",callSwingper R_callswing_envelope). Overridable seam: JTextPane drives its two-way sync through RTE's Delta value instead of HTML, so it replaces this wiring rather than adding a second, conflicting listener.- Overrides:
wirePeerToDocumentin classJEditorPane
-
pushTextToPeer
Description copied from class:JEditorPanePushessetText's markup into RTE'shtmlValueunderpreventPeerEvents(so the peer's value-change listener doesn't re-mirror our own write back into the Document). Overridable seam: JTextPane pushes through its Delta serializer instead, driven by the Document mutationsuper.setTextalready made, so it overrides this to a no-op.- Overrides:
pushTextToPeerin classJEditorPane
-
setCharacterAttributes
Appliesattrto the pane's input attributes whatever is selected, which makes no visible change: the JDK's no-selection behaviour, where the JDK would style a selection. To style existing text callgetStyledDocument().setCharacterAttributes(...). -
getCharacterAttributes
The pending-input character attributes (JDK returns these at an empty selection). -
setParagraphAttributes
Applies paragraphattrto the first paragraph — the JDK's behaviour at an empty selection (setParagraphAttributes(0, 0, …)), which does render (e.g. alignment). Offset-based styling of other paragraphs goes throughgetStyledDocument().setParagraphAttributes(offset, len, …). -
getParagraphAttributes
Paragraph attributes of the first paragraph (JDK reads these at the caret). -
getInputAttributes
- Returns:
- the kit's pending-input attribute set — the JDK's own home for it,
so a
createDefaultEditorKit()override that seeds attributes is observable here
-
addStyle
-
removeStyle
-
getStyle
-
setLogicalStyle
Sets the logical style of the first paragraph (JDK applies it at the caret). -
getLogicalStyle
Logical style of the first paragraph. -
insertIcon
-
insertComponent
-
setEditorKit
Description copied from class:JEditorPaneInstall an editor kit. Every kit is stored and read back byJEditorPane.getEditorKit(); only aHTMLEditorKitadditionally takes effect, its stylesheet binding to the peer so rules added to it (before or after this call) style the pane's content. Any other kind WARNs — without a route to the Vaadin peer, installing it could only pretend.Two JDK behaviours are deliberately not reproduced. The document is left alone — the JDK replaces it with
kit.createDefaultDocument(), whereas here the element model follows the content type instead (JEditorPane.setContentType(String)), so installing a kit never silently changes whatgetDocument()returns. And the content type is left alone; set it explicitly if it matters.- Overrides:
setEditorKitin classJEditorPane
-
createDefaultEditorKit
- Returns:
- the kit this pane holds; called from the constructor as the JDK calls it, so an override cannot read its own subclass's fields
-
getStyledEditorKit
- Returns:
- the kit
createDefaultEditorKit()built at construction — where the JDK castsgetEditorKit(), which here answers only what the migrator installed (seeJEditorPane.getEditorKit())
-
getUIClassID
- Overrides:
getUIClassIDin classJEditorPane
-