- java.lang.Object
-
- java.awt.Component
-
- java.awt.Container
-
- javax.swing.JComponent
-
- javax.swing.text.JTextComponent
-
- javax.swing.JEditorPane
-
- All Implemented Interfaces:
- ImageObserver, MenuContainer, Serializable, Accessible, Scrollable
- Direct Known Subclasses:
- JTextPane
public class JEditorPane extends JTextComponent
A text component to edit various kinds of content. You can find how-to information and examples of using editor panes in Using Text Components, a section in The Java Tutorial.This component uses implementations of the
EditorKit
to accomplish its behavior. It effectively morphs into the proper kind of text editor for the kind of content it is given. The content type that editor is bound to at any given time is determined by theEditorKit
currently installed. If the content is set to a new URL, its type is used to determine theEditorKit
that should be used to load the content.By default, the following types of content are known:
- text/plain
- Plain text, which is the default the type given isn't
recognized. The kit used in this case is an extension of
DefaultEditorKit
that produces a wrapped plain text view. - text/html
- HTML text. The kit used in this case is the class
javax.swing.text.html.HTMLEditorKit
which provides HTML 3.2 support. - text/rtf
- RTF text. The kit used in this case is the class
javax.swing.text.rtf.RTFEditorKit
which provides a limited support of the Rich Text Format.
There are several ways to load content into this component.
-
The
setText
method can be used to initialize the component from a string. In this case the currentEditorKit
will be used, and the content type will be expected to be of this type. -
The
read
method can be used to initialize the component from aReader
. Note that if the content type is HTML, relative references (e.g. for things like images) can't be resolved unless the <base> tag is used or the Base property onHTMLDocument
is set. In this case the currentEditorKit
will be used, and the content type will be expected to be of this type. -
The
setPage
method can be used to initialize the component from a URL. In this case, the content type will be determined from the URL, and the registeredEditorKit
for that content type will be set.
Some kinds of content may provide hyperlink support by generating hyperlink events. The HTML
EditorKit
will generate hyperlink events if theJEditorPane
is not editable (JEditorPane.setEditable(false);
has been called). If HTML frames are embedded in the document, the typical response would be to change a portion of the current document. The following code fragment is a possible hyperlink listener implementation, that treats HTML frame events specially, and simply displays any other activated hyperlinks.class Hyperactive implements HyperlinkListener { public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { JEditorPane pane = (JEditorPane) e.getSource(); if (e instanceof HTMLFrameHyperlinkEvent) { HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent)e; HTMLDocument doc = (HTMLDocument)pane.getDocument(); doc.processHTMLFrameHyperlinkEvent(evt); } else { try { pane.setPage(e.getURL()); } catch (Throwable t) { t.printStackTrace(); } } } } }
For information on customizing how text/html is rendered please see
W3C_LENGTH_UNITS
andHONOR_DISPLAY_PROPERTIES
Culturally dependent information in some documents is handled through a mechanism called character encoding. Character encoding is an unambiguous mapping of the members of a character set (letters, ideographs, digits, symbols, or control functions) to specific numeric code values. It represents the way the file is stored. Example character encodings are ISO-8859-1, ISO-8859-5, Shift-jis, Euc-jp, and UTF-8. When the file is passed to an user agent (
JEditorPane
) it is converted to the document character set (ISO-10646 aka Unicode).There are multiple ways to get a character set mapping to happen with
JEditorPane
.-
One way is to specify the character set as a parameter of the MIME
type. This will be established by a call to the
setContentType
method. If the content is loaded by thesetPage
method the content type will have been set according to the specification of the URL. It the file is loaded directly, the content type would be expected to have been set prior to loading. -
Another way the character set can be specified is in the document itself.
This requires reading the document prior to determining the character set
that is desired. To handle this, it is expected that the
EditorKit
.read operation throw aChangedCharSetException
which will be caught. The read is then restarted with a new Reader that uses the character set specified in theChangedCharSetException
(which is anIOException
).
- Newlines
- For a discussion on how newlines are handled, see DefaultEditorKit.
Warning: Swing is not thread safe. For more information see Swing's Threading Policy.
Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the
java.beans
package. Please seeXMLEncoder
.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class and Description protected class
JEditorPane.AccessibleJEditorPane
This class implements accessibility support for theJEditorPane
class.protected class
JEditorPane.AccessibleJEditorPaneHTML
This class provides support forAccessibleHypertext
, and is used in instances where theEditorKit
installed in thisJEditorPane
is an instance ofHTMLEditorKit
.protected class
JEditorPane.JEditorPaneAccessibleHypertextSupport
What's returned byAccessibleJEditorPaneHTML.getAccessibleText
.-
Nested classes/interfaces inherited from class javax.swing.text.JTextComponent
JTextComponent.AccessibleJTextComponent, JTextComponent.DropLocation, JTextComponent.KeyBinding
-
Nested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
-
Nested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainer
-
Nested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
-
-
Field Summary
Fields Modifier and Type Field and Description static String
HONOR_DISPLAY_PROPERTIES
Key for a client property used to indicate whether the default font and foreground color from the component are used if a font or foreground color is not specified in the styled text.static String
W3C_LENGTH_UNITS
Key for a client property used to indicate whether w3c compliant length units are used for html rendering.-
Fields inherited from class javax.swing.text.JTextComponent
DEFAULT_KEYMAP, FOCUS_ACCELERATOR_KEY
-
Fields inherited from class javax.swing.JComponent
accessibleContext, 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
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
-
-
Constructor Summary
Constructors Constructor and Description JEditorPane()
Creates a newJEditorPane
.JEditorPane(String url)
Creates aJEditorPane
based on a string containing a URL specification.JEditorPane(String type, String text)
Creates aJEditorPane
that has been initialized to the given text.JEditorPane(URL initialPage)
Creates aJEditorPane
based on a specified URL for input.
-
Method Summary
Methods Modifier and Type Method and Description void
addHyperlinkListener(HyperlinkListener listener)
Adds a hyperlink listener for notification of any changes, for example when a link is selected and entered.protected EditorKit
createDefaultEditorKit()
Creates the default editor kit (PlainEditorKit
) for when the component is first created.static EditorKit
createEditorKitForContentType(String type)
Creates a handler for the given type from the default registry of editor kits.void
fireHyperlinkUpdate(HyperlinkEvent e)
Notifies all listeners that have registered interest for notification on this event type.AccessibleContext
getAccessibleContext()
Gets the AccessibleContext associated with this JEditorPane.String
getContentType()
Gets the type of content that this editor is currently set to deal with.EditorKit
getEditorKit()
Fetches the currently installed kit for handling content.static String
getEditorKitClassNameForContentType(String type)
Returns the currently registeredEditorKit
class name for the typetype
.EditorKit
getEditorKitForContentType(String type)
Fetches the editor kit to use for the given type of content.HyperlinkListener[]
getHyperlinkListeners()
Returns an array of all theHyperLinkListener
s added to this JEditorPane with addHyperlinkListener().URL
getPage()
Gets the current URL being displayed.Dimension
getPreferredSize()
Returns the preferred size for theJEditorPane
.boolean
getScrollableTracksViewportHeight()
Returns true if a viewport should always force the height of thisScrollable
to match the height of the viewport.boolean
getScrollableTracksViewportWidth()
Returns true if a viewport should always force the width of thisScrollable
to match the width of the viewport.protected InputStream
getStream(URL page)
Fetches a stream for the given URL, which is about to be loaded by thesetPage
method.String
getText()
Returns the text contained in thisTextComponent
in terms of the content type of this editor.String
getUIClassID()
Gets the class ID for the UI.protected String
paramString()
Returns a string representation of thisJEditorPane
.void
read(InputStream in, Object desc)
This method initializes from a stream.static void
registerEditorKitForContentType(String type, String classname)
Establishes the default bindings oftype
toclassname
.static void
registerEditorKitForContentType(String type, String classname, ClassLoader loader)
Establishes the default bindings oftype
toclassname
.void
removeHyperlinkListener(HyperlinkListener listener)
Removes a hyperlink listener.void
replaceSelection(String content)
Replaces the currently selected content with new content represented by the given string.void
scrollToReference(String reference)
Scrolls the view to the given reference location (that is, the value returned by theUL.getRef
method for the URL being displayed).void
setContentType(String type)
Sets the type of content that this editor handles.void
setEditorKit(EditorKit kit)
Sets the currently installed kit for handling content.void
setEditorKitForContentType(String type, EditorKit k)
Directly sets the editor kit to use for the given type.void
setPage(String url)
Sets the current URL being displayed.void
setPage(URL page)
Sets the current URL being displayed.void
setText(String t)
Sets the text of thisTextComponent
to the specified content, which is expected to be in the format of the content type of this editor.-
Methods inherited from class javax.swing.text.JTextComponent
addCaretListener, addInputMethodListener, addKeymap, copy, cut, fireCaretUpdate, getActions, getCaret, getCaretColor, getCaretListeners, getCaretPosition, getDisabledTextColor, getDocument, getDragEnabled, getDropLocation, getDropMode, getFocusAccelerator, getHighlighter, getInputMethodRequests, getKeymap, getKeymap, getMargin, getNavigationFilter, getPreferredScrollableViewportSize, getPrintable, getScrollableBlockIncrement, getScrollableUnitIncrement, getSelectedText, getSelectedTextColor, getSelectionColor, getSelectionEnd, getSelectionStart, getText, getToolTipText, getUI, isEditable, loadKeymap, modelToView, moveCaretPosition, paste, print, print, print, processInputMethodEvent, read, removeCaretListener, removeKeymap, removeNotify, restoreComposedText, saveComposedText, select, selectAll, setCaret, setCaretColor, setCaretPosition, setComponentOrientation, setDisabledTextColor, setDocument, setDragEnabled, setDropMode, setEditable, setFocusAccelerator, setHighlighter, setKeymap, setMargin, setNavigationFilter, setSelectedTextColor, setSelectionColor, setSelectionEnd, setSelectionStart, setUI, updateUI, viewToModel, write
-
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, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, 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, processKeyEvent, processMouseEvent, processMouseMotionEvent, 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, 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, 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, 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, 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, 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, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
-
-
-
-
Field Detail
-
W3C_LENGTH_UNITS
public static final String W3C_LENGTH_UNITS
Key for a client property used to indicate whether w3c compliant length units are used for html rendering.By default this is not enabled; to enable it set the client
property
with this name toBoolean.TRUE
.- Since:
- 1.5
- See Also:
- Constant Field Values
-
HONOR_DISPLAY_PROPERTIES
public static final String HONOR_DISPLAY_PROPERTIES
Key for a client property used to indicate whether the default font and foreground color from the component are used if a font or foreground color is not specified in the styled text.The default varies based on the look and feel; to enable it set the client
property
with this name toBoolean.TRUE
.- Since:
- 1.5
- See Also:
- Constant Field Values
-
-
Constructor Detail
-
JEditorPane
public JEditorPane()
Creates a newJEditorPane
. The document model is set tonull
.
-
JEditorPane
public JEditorPane(URL initialPage) throws IOException
Creates aJEditorPane
based on a specified URL for input.- Parameters:
initialPage
- the URL- Throws:
IOException
- if the URL isnull
or cannot be accessed
-
JEditorPane
public JEditorPane(String url) throws IOException
Creates aJEditorPane
based on a string containing a URL specification.- Parameters:
url
- the URL- Throws:
IOException
- if the URL isnull
or cannot be accessed
-
JEditorPane
public JEditorPane(String type, String text)
Creates aJEditorPane
that has been initialized to the given text. This is a convenience constructor that calls thesetContentType
andsetText
methods.- Parameters:
type
- mime type of the given texttext
- the text to initialize with; may benull
- Throws:
NullPointerException
- if thetype
parameter isnull
-
-
Method Detail
-
addHyperlinkListener
public void addHyperlinkListener(HyperlinkListener listener)
Adds a hyperlink listener for notification of any changes, for example when a link is selected and entered.- Parameters:
listener
- the listener
-
removeHyperlinkListener
public void removeHyperlinkListener(HyperlinkListener listener)
Removes a hyperlink listener.- Parameters:
listener
- the listener
-
getHyperlinkListeners
public HyperlinkListener[] getHyperlinkListeners()
Returns an array of all theHyperLinkListener
s added to this JEditorPane with addHyperlinkListener().- Returns:
- all of the
HyperLinkListener
s added or an empty array if no listeners have been added - Since:
- 1.4
-
fireHyperlinkUpdate
public void fireHyperlinkUpdate(HyperlinkEvent e)
Notifies all listeners that have registered interest for notification on this event type. This is normally called by the currently installedEditorKit
if a content type that supports hyperlinks is currently active and there was activity with a link. The listener list is processed last to first.- Parameters:
e
- the event- See Also:
EventListenerList
-
setPage
public void setPage(URL page) throws IOException
Sets the current URL being displayed. The content type of the pane is set, and if the editor kit for the pane is non-null
, then a new default document is created and the URL is read into it. If the URL contains and reference location, the location will be scrolled to by calling thescrollToReference
method. If the desired URL is the one currently being displayed, the document will not be reloaded. To force a document reload it is necessary to clear the stream description property of the document. The following code shows how this can be done:Document doc = jEditorPane.getDocument(); doc.putProperty(Document.StreamDescriptionProperty, null);
If the desired URL is not the one currently being displayed, thegetStream
method is called to give subclasses control over the stream provided.This may load either synchronously or asynchronously depending upon the document returned by the
EditorKit
. If theDocument
is of typeAbstractDocument
and has a value returned byAbstractDocument.getAsynchronousLoadPriority
that is greater than or equal to zero, the page will be loaded on a separate thread using that priority.If the document is loaded synchronously, it will be filled in with the stream prior to being installed into the editor with a call to
setDocument
, which is bound and will fire a property change event. If anIOException
is thrown the partially loaded document will be discarded and neither the document or page property change events will be fired. If the document is successfully loaded and installed, a view will be built for it by the UI which will then be scrolled if necessary, and then the page property change event will be fired.If the document is loaded asynchronously, the document will be installed into the editor immediately using a call to
setDocument
which will fire a document property change event, then a thread will be created which will begin doing the actual loading. In this case, the page property change event will not be fired by the call to this method directly, but rather will be fired when the thread doing the loading has finished. It will also be fired on the event-dispatch thread. Since the calling thread can not throw anIOException
in the event of failure on the other thread, the page property change event will be fired when the other thread is done whether the load was successful or not.- Parameters:
page
- the URL of the page- Throws:
IOException
- for anull
or invalid page specification, or exception from the stream being read- See Also:
getPage()
-
read
public void read(InputStream in, Object desc) throws IOException
This method initializes from a stream. If the kit is set to be of typeHTMLEditorKit
, and thedesc
parameter is anHTMLDocument
, then it invokes theHTMLEditorKit
to initiate the read. Otherwise it calls the superclass method which loads the model as plain text.- Parameters:
in
- the stream from which to readdesc
- an object describing the stream- Throws:
IOException
- as thrown by the stream being used to initialize- See Also:
JTextComponent.read(java.io.Reader, java.lang.Object)
,JTextComponent.setDocument(javax.swing.text.Document)
-
getStream
protected InputStream getStream(URL page) throws IOException
Fetches a stream for the given URL, which is about to be loaded by thesetPage
method. By default, this simply opens the URL and returns the stream. This can be reimplemented to do useful things like fetch the stream from a cache, monitor the progress of the stream, etc.This method is expected to have the the side effect of establishing the content type, and therefore setting the appropriate
EditorKit
to use for loading the stream.If this the stream was an http connection, redirects will be followed and the resulting URL will be set as the
Document.StreamDescriptionProperty
so that relative URL's can be properly resolved.- Parameters:
page
- the URL of the page- Throws:
IOException
-
scrollToReference
public void scrollToReference(String reference)
Scrolls the view to the given reference location (that is, the value returned by theUL.getRef
method for the URL being displayed). By default, this method only knows how to locate a reference in an HTMLDocument. The implementation calls thescrollRectToVisible
method to accomplish the actual scrolling. If scrolling to a reference location is needed for document types other than HTML, this method should be reimplemented. This method will have no effect if the component is not visible.- Parameters:
reference
- the named location to scroll to
-
getPage
public URL getPage()
Gets the current URL being displayed. If a URL was not specified in the creation of the document, this will returnnull
, and relative URL's will not be resolved.- Returns:
- the URL, or
null
if none
-
setPage
public void setPage(String url) throws IOException
Sets the current URL being displayed.- Parameters:
url
- the URL for display- Throws:
IOException
- for anull
or invalid URL specification
-
getUIClassID
public String getUIClassID()
Gets the class ID for the UI.- Overrides:
getUIClassID
in classJComponent
- Returns:
- the string "EditorPaneUI"
- See Also:
JComponent.getUIClassID()
,UIDefaults.getUI(javax.swing.JComponent)
-
createDefaultEditorKit
protected EditorKit createDefaultEditorKit()
Creates the default editor kit (PlainEditorKit
) for when the component is first created.- Returns:
- the editor kit
-
getEditorKit
public EditorKit getEditorKit()
Fetches the currently installed kit for handling content.createDefaultEditorKit
is called to set up a default if necessary.- Returns:
- the editor kit
-
getContentType
public final String getContentType()
Gets the type of content that this editor is currently set to deal with. This is defined to be the type associated with the currently installedEditorKit
.- Returns:
- the content type,
null
if no editor kit set
-
setContentType
public final void setContentType(String type)
Sets the type of content that this editor handles. This callsgetEditorKitForContentType
, and thensetEditorKit
if an editor kit can be successfully located. This is mostly convenience method that can be used as an alternative to callingsetEditorKit
directly.If there is a charset definition specified as a parameter of the content type specification, it will be used when loading input streams using the associated
EditorKit
. For example if the type is specified astext/html; charset=EUC-JP
the content will be loaded using theEditorKit
registered fortext/html
and the Reader provided to theEditorKit
to load unicode into the document will use theEUC-JP
charset for translating to unicode. If the type is not recognized, the content will be loaded using theEditorKit
registered for plain text,text/plain
.- Parameters:
type
- the non-null
mime type for the content editing support- Throws:
NullPointerException
- if thetype
parameter isnull
- See Also:
getContentType()
-
setEditorKit
public void setEditorKit(EditorKit kit)
Sets the currently installed kit for handling content. This is the bound property that establishes the content type of the editor. Any old kit is first deinstalled, then if kit is non-null
, the new kit is installed, and a default document created for it. APropertyChange
event ("editorKit") is always fired whensetEditorKit
is called.NOTE: This has the side effect of changing the model, because the
EditorKit
is the source of how a particular type of content is modeled. This method will causesetDocument
to be called on behalf of the caller to ensure integrity of the internal state.- Parameters:
kit
- the desired editor behavior- See Also:
getEditorKit()
-
getEditorKitForContentType
public EditorKit getEditorKitForContentType(String type)
Fetches the editor kit to use for the given type of content. This is called when a type is requested that doesn't match the currently installed type. If the component doesn't have anEditorKit
registered for the given type, it will try to create anEditorKit
from the defaultEditorKit
registry. If that fails, aPlainEditorKit
is used on the assumption that all text documents can be represented as plain text.This method can be reimplemented to use some other kind of type registry. This can be reimplemented to use the Java Activation Framework, for example.
- Parameters:
type
- the non-null
content type- Returns:
- the editor kit
-
setEditorKitForContentType
public void setEditorKitForContentType(String type, EditorKit k)
Directly sets the editor kit to use for the given type. A look-and-feel implementation might use this in conjunction withcreateEditorKitForContentType
to install handlers for content types with a look-and-feel bias.- Parameters:
type
- the non-null
content typek
- the editor kit to be set
-
replaceSelection
public void replaceSelection(String content)
Replaces the currently selected content with new content represented by the given string. If there is no selection this amounts to an insert of the given text. If there is no replacement text (i.e. the content string is empty ornull
) this amounts to a removal of the current selection. The replacement text will have the attributes currently defined for input. If the component is not editable, beep and return.- Overrides:
replaceSelection
in classJTextComponent
- Parameters:
content
- the content to replace the selection with. This value can benull
-
createEditorKitForContentType
public static EditorKit createEditorKitForContentType(String type)
Creates a handler for the given type from the default registry of editor kits. The registry is created if necessary. If the registered class has not yet been loaded, an attempt is made to dynamically load the prototype of the kit for the given type. If the type was registered with aClassLoader
, thatClassLoader
will be used to load the prototype. If there was no registeredClassLoader
,Class.forName
will be used to load the prototype.Once a prototype
EditorKit
instance is successfully located, it is cloned and the clone is returned.- Parameters:
type
- the content type- Returns:
- the editor kit, or
null
if there is nothing registered for the given type
-
registerEditorKitForContentType
public static void registerEditorKitForContentType(String type, String classname)
Establishes the default bindings oftype
toclassname
. The class will be dynamically loaded later when actually needed, and can be safely changed before attempted uses to avoid loading unwanted classes. The prototypeEditorKit
will be loaded withClass.forName
when registered with this method.- Parameters:
type
- the non-null
content typeclassname
- the class to load later
-
registerEditorKitForContentType
public static void registerEditorKitForContentType(String type, String classname, ClassLoader loader)
Establishes the default bindings oftype
toclassname
. The class will be dynamically loaded later when actually needed using the givenClassLoader
, and can be safely changed before attempted uses to avoid loading unwanted classes.- Parameters:
type
- the non-null
content typeclassname
- the class to load laterloader
- theClassLoader
to use to load the name
-
getEditorKitClassNameForContentType
public static String getEditorKitClassNameForContentType(String type)
Returns the currently registeredEditorKit
class name for the typetype
.- Parameters:
type
- the non-null
content type- Since:
- 1.3
-
getPreferredSize
public Dimension getPreferredSize()
Returns the preferred size for theJEditorPane
. The preferred size forJEditorPane
is slightly altered from the preferred size of the superclass. If the size of the viewport has become smaller than the minimum size of the component, the scrollable definition for tracking width or height will turn to false. The default viewport layout will give the preferred size, and that is not desired in the case where the scrollable is tracking. In that case the normal preferred size is adjusted to the minimum size. This allows things like HTML tables to shrink down to their minimum size and then be laid out at their minimum size, refusing to shrink any further.- Overrides:
getPreferredSize
in classJComponent
- Returns:
- a
Dimension
containing the preferred size - See Also:
JComponent.setPreferredSize(java.awt.Dimension)
,ComponentUI
-
setText
public void setText(String t)
Sets the text of thisTextComponent
to the specified content, which is expected to be in the format of the content type of this editor. For example, if the type is set totext/html
the string should be specified in terms of HTML.This is implemented to remove the contents of the current document, and replace them by parsing the given string using the current
EditorKit
. This gives the semantics of the superclass by not changing out the model, while supporting the content type currently set on this component. The assumption is that the previous content is relatively small, and that the previous content doesn't have side effects. Both of those assumptions can be violated and cause undesirable results. To avoid this, create a new document,getEditorKit().createDefaultDocument()
, and replace the existingDocument
with the new one. You are then assured the previousDocument
won't have any lingering state.- Leaving the existing model in place means that the old view will be torn down, and a new view created, where replacing the document would avoid the tear down of the old view.
- Some formats (such as HTML) can install things into the document that can influence future contents. HTML can have style information embedded that would influence the next content installed unexpectedly.
An alternative way to load this component with a string would be to create a StringReader and call the read method. In this case the model would be replaced after it was initialized with the contents of the string.
- Overrides:
setText
in classJTextComponent
- Parameters:
t
- the new text to be set; ifnull
the old text will be deleted- See Also:
getText()
-
getText
public String getText()
Returns the text contained in thisTextComponent
in terms of the content type of this editor. If an exception is thrown while attempting to retrieve the text,null
will be returned. This is implemented to callJTextComponent.write
with aStringWriter
.- Overrides:
getText
in classJTextComponent
- Returns:
- the text
- See Also:
setText(java.lang.String)
-
getScrollableTracksViewportWidth
public boolean getScrollableTracksViewportWidth()
Returns true if a viewport should always force the width of thisScrollable
to match the width of the viewport.- Specified by:
getScrollableTracksViewportWidth
in interfaceScrollable
- Overrides:
getScrollableTracksViewportWidth
in classJTextComponent
- Returns:
- true if a viewport should force the Scrollables width to match its own, false otherwise
-
getScrollableTracksViewportHeight
public boolean getScrollableTracksViewportHeight()
Returns true if a viewport should always force the height of thisScrollable
to match the height of the viewport.- Specified by:
getScrollableTracksViewportHeight
in interfaceScrollable
- Overrides:
getScrollableTracksViewportHeight
in classJTextComponent
- Returns:
- true if a viewport should force the
Scrollable
's height to match its own, false otherwise
-
paramString
protected String paramString()
Returns a string representation of thisJEditorPane
. This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not benull
.- Overrides:
paramString
in classJTextComponent
- Returns:
- a string representation of this
JEditorPane
-
getAccessibleContext
public AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JEditorPane. For editor panes, the AccessibleContext takes the form of an AccessibleJEditorPane. A new AccessibleJEditorPane instance is created if necessary.- Specified by:
getAccessibleContext
in interfaceAccessible
- Overrides:
getAccessibleContext
in classJTextComponent
- Returns:
- an AccessibleJEditorPane that serves as the AccessibleContext of this JEditorPane
-
-
Nederlandse vertaling
U hebt gevraagd om deze site in het Nederlands te bezoeken. Voor nu wordt alleen de interface vertaald, maar nog niet alle inhoud.Als je me wilt helpen met vertalingen, is je bijdrage welkom. Het enige dat u hoeft te doen, is u op de site registreren en mij een bericht sturen waarin u wordt gevraagd om u toe te voegen aan de groep vertalers, zodat u de gewenste pagina's kunt vertalen. Een link onderaan elke vertaalde pagina geeft aan dat u de vertaler bent en heeft een link naar uw profiel.
Bij voorbaat dank.
Document heeft de 11/06/2005 gemaakt, de laatste keer de 04/03/2020 gewijzigd
Bron van het afgedrukte document:https://www.gaudry.be/nl/java-api-rf-javax/swing/jeditorpane.html
De infobrol is een persoonlijke site waarvan de inhoud uitsluitend mijn verantwoordelijkheid is. De tekst is beschikbaar onder CreativeCommons-licentie (BY-NC-SA). Meer info op de gebruiksvoorwaarden en de auteur.
Referenties
Deze verwijzingen en links verwijzen naar documenten die geraadpleegd zijn tijdens het schrijven van deze pagina, of die aanvullende informatie kunnen geven, maar de auteurs van deze bronnen kunnen niet verantwoordelijk worden gehouden voor de inhoud van deze pagina.
De auteur Deze site is als enige verantwoordelijk voor de manier waarop de verschillende concepten, en de vrijheden die met de referentiewerken worden genomen, hier worden gepresenteerd. Vergeet niet dat u meerdere broninformatie moet doorgeven om het risico op fouten te verkleinen.