/* * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.swing; import java.awt.*; import java.lang.reflect.*; import java.net.*; import java.util.*; import java.io.*; import javax.swing.plaf.*; import javax.swing.text.*; import javax.swing.event.*; import javax.swing.text.html.*; import javax.accessibility.*; /** * 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 the EditorKit
currently
* installed. If the content is set to a new URL, its type is used
* to determine the EditorKit
that should be used to
* load the content.
*
* By default, the following types of content are known: *
DefaultEditorKit
that produces a wrapped plain text view.
* javax.swing.text.html.HTMLEditorKit
* which provides HTML 3.2 support.
* 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. *
EditorKit
will be used, and the content type will be
* expected to be of this type.
* Reader
. 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
* on HTMLDocument
is set.
* In this case the current EditorKit
will be used,
* and the content type will be expected to be of this type.
* EditorKit
* 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 the JEditorPane
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 * {@link #W3C_LENGTH_UNITS} and {@link #HONOR_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
.
*
EditorKit
.read operation throw a
* ChangedCharSetException
which will
* be caught. The read is then restarted with a new Reader that uses
* the character set specified in the ChangedCharSetException
* (which is an IOException
).
* *
* 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 JavaBeans™
* has been added to the java.beans
package.
* Please see {@link java.beans.XMLEncoder}.
*
* @beaninfo
* attribute: isContainer false
* description: A text component to edit various types of content.
*
* @author Timothy Prinzing
*/
public class JEditorPane extends JTextComponent {
/**
* Creates a new JEditorPane
.
* The document model is set to null
.
*/
public JEditorPane() {
super();
setFocusCycleRoot(true);
setFocusTraversalPolicy(new LayoutFocusTraversalPolicy() {
public Component getComponentAfter(Container focusCycleRoot,
Component aComponent) {
if (focusCycleRoot != JEditorPane.this ||
(!isEditable() && getComponentCount() > 0)) {
return super.getComponentAfter(focusCycleRoot,
aComponent);
} else {
Container rootAncestor = getFocusCycleRootAncestor();
return (rootAncestor != null)
? rootAncestor.getFocusTraversalPolicy().
getComponentAfter(rootAncestor,
JEditorPane.this)
: null;
}
}
public Component getComponentBefore(Container focusCycleRoot,
Component aComponent) {
if (focusCycleRoot != JEditorPane.this ||
(!isEditable() && getComponentCount() > 0)) {
return super.getComponentBefore(focusCycleRoot,
aComponent);
} else {
Container rootAncestor = getFocusCycleRootAncestor();
return (rootAncestor != null)
? rootAncestor.getFocusTraversalPolicy().
getComponentBefore(rootAncestor,
JEditorPane.this)
: null;
}
}
public Component getDefaultComponent(Container focusCycleRoot)
{
return (focusCycleRoot != JEditorPane.this ||
(!isEditable() && getComponentCount() > 0))
? super.getDefaultComponent(focusCycleRoot)
: null;
}
protected boolean accept(Component aComponent) {
return (aComponent != JEditorPane.this)
? super.accept(aComponent)
: false;
}
});
LookAndFeel.installProperty(this,
"focusTraversalKeysForward",
JComponent.
getManagingFocusForwardTraversalKeys());
LookAndFeel.installProperty(this,
"focusTraversalKeysBackward",
JComponent.
getManagingFocusBackwardTraversalKeys());
}
/**
* Creates a JEditorPane
based on a specified URL for input.
*
* @param initialPage the URL
* @exception IOException if the URL is null
* or cannot be accessed
*/
public JEditorPane(URL initialPage) throws IOException {
this();
setPage(initialPage);
}
/**
* Creates a JEditorPane
based on a string containing
* a URL specification.
*
* @param url the URL
* @exception IOException if the URL is null
or
* cannot be accessed
*/
public JEditorPane(String url) throws IOException {
this();
setPage(url);
}
/**
* Creates a JEditorPane
that has been initialized
* to the given text. This is a convenience constructor that calls the
* setContentType
and setText
methods.
*
* @param type mime type of the given text
* @param text the text to initialize with; may be null
* @exception NullPointerException if the type
parameter
* is null
*/
public JEditorPane(String type, String text) {
this();
setContentType(type);
setText(text);
}
/**
* Adds a hyperlink listener for notification of any changes, for example
* when a link is selected and entered.
*
* @param listener the listener
*/
public synchronized void addHyperlinkListener(HyperlinkListener listener) {
listenerList.add(HyperlinkListener.class, listener);
}
/**
* Removes a hyperlink listener.
*
* @param listener the listener
*/
public synchronized void removeHyperlinkListener(HyperlinkListener listener) {
listenerList.remove(HyperlinkListener.class, listener);
}
/**
* Returns an array of all the HyperLinkListener
s added
* to this JEditorPane with addHyperlinkListener().
*
* @return all of the HyperLinkListener
s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public synchronized HyperlinkListener[] getHyperlinkListeners() {
return listenerList.getListeners(javax.swing.event.HyperlinkListener.class);
}
/**
* Notifies all listeners that have registered interest for
* notification on this event type. This is normally called
* by the currently installed EditorKit
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.
*
* @param e the event
* @see EventListenerList
*/
public void fireHyperlinkUpdate(HyperlinkEvent e) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==HyperlinkListener.class) {
((HyperlinkListener)listeners[i+1]).hyperlinkUpdate(e);
}
}
}
/**
* 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 the scrollToReference
* 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, the
getStream
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 the Document
is of type
* AbstractDocument
and has a value returned by
* AbstractDocument.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 an
* IOException
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
* This method is expected to have the the side effect of
* establishing the content type, and therefore setting the
* appropriate
* If this the stream was an http connection, redirects
* will be followed and the resulting URL will be set as
* the
* 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
* NOTE: This has the side effect of changing the model,
* because the
* 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.
*
* @param type the non-
* Once a prototype
* This is implemented to remove the contents of the current document,
* and replace them by parsing the given string using the current
*
* 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.
*
* @param t the new text to be set; if
* By default this is not enabled; to enable
* it set the client {@link #putClientProperty property} with this name
* to
* The default varies based on the look and feel;
* to enable it set the client {@link #putClientProperty property} with
* this name to
* 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 JavaBeans™
* has been added to the
* 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 JavaBeans™
* has been added to the 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 an IOException
* 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.
*
* @param page the URL of the page
* @exception IOException for a null
or invalid
* page specification, or exception from the stream being read
* @see #getPage
* @beaninfo
* description: the URL used to set content
* bound: true
* expert: true
*/
public void setPage(URL page) throws IOException {
if (page == null) {
throw new IOException("invalid url");
}
URL loaded = getPage();
// reset scrollbar
if (!page.equals(loaded) && page.getRef() == null) {
scrollRectToVisible(new Rectangle(0,0,1,1));
}
boolean reloaded = false;
Object postData = getPostData();
if ((loaded == null) || !loaded.sameFile(page) || (postData != null)) {
// different url or POST method, load the new content
int p = getAsynchronousLoadPriority(getDocument());
if (p < 0) {
// open stream synchronously
InputStream in = getStream(page);
if (kit != null) {
Document doc = initializeModel(kit, page);
// At this point, one could either load up the model with no
// view notifications slowing it down (i.e. best synchronous
// behavior) or set the model and start to feed it on a separate
// thread (best asynchronous behavior).
p = getAsynchronousLoadPriority(doc);
if (p >= 0) {
// load asynchronously
setDocument(doc);
synchronized(this) {
pageLoader = new PageLoader(doc, in, loaded, page);
pageLoader.execute();
}
return;
}
read(in, doc);
setDocument(doc);
reloaded = true;
}
} else {
// we may need to cancel background loading
if (pageLoader != null) {
pageLoader.cancel(true);
}
// Do everything in a background thread.
// Model initialization is deferred to that thread, too.
pageLoader = new PageLoader(null, null, loaded, page);
pageLoader.execute();
return;
}
}
final String reference = page.getRef();
if (reference != null) {
if (!reloaded) {
scrollToReference(reference);
}
else {
// Have to scroll after painted.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
scrollToReference(reference);
}
});
}
getDocument().putProperty(Document.StreamDescriptionProperty, page);
}
firePropertyChange("page", loaded, page);
}
/**
* Create model and initialize document properties from page properties.
*/
private Document initializeModel(EditorKit kit, URL page) {
Document doc = kit.createDefaultDocument();
if (pageProperties != null) {
// transfer properties discovered in stream to the
// document property collection.
for (EnumerationHTMLEditorKit
, and the
* desc
parameter is an HTMLDocument
,
* then it invokes the HTMLEditorKit
to initiate
* the read. Otherwise it calls the superclass
* method which loads the model as plain text.
*
* @param in the stream from which to read
* @param desc an object describing the stream
* @exception IOException as thrown by the stream being
* used to initialize
* @see JTextComponent#read
* @see #setDocument
*/
public void read(InputStream in, Object desc) throws IOException {
if (desc instanceof HTMLDocument &&
kit instanceof HTMLEditorKit) {
HTMLDocument hdoc = (HTMLDocument) desc;
setDocument(hdoc);
read(in, hdoc);
} else {
String charset = (String) getClientProperty("charset");
Reader r = (charset != null) ? new InputStreamReader(in, charset) :
new InputStreamReader(in);
super.read(r, desc);
}
}
/**
* This method invokes the EditorKit
to initiate a
* read. In the case where a ChangedCharSetException
* is thrown this exception will contain the new CharSet.
* Therefore the read
operation
* is then restarted after building a new Reader with the new charset.
*
* @param in the inputstream to use
* @param doc the document to load
*
*/
void read(InputStream in, Document doc) throws IOException {
if (! Boolean.TRUE.equals(doc.getProperty("IgnoreCharsetDirective"))) {
final int READ_LIMIT = 1024 * 10;
in = new BufferedInputStream(in, READ_LIMIT);
in.mark(READ_LIMIT);
}
try {
String charset = (String) getClientProperty("charset");
Reader r = (charset != null) ? new InputStreamReader(in, charset) :
new InputStreamReader(in);
kit.read(r, doc, 0);
} catch (BadLocationException e) {
throw new IOException(e.getMessage());
} catch (ChangedCharSetException changedCharSetException) {
String charSetSpec = changedCharSetException.getCharSetSpec();
if (changedCharSetException.keyEqualsCharSet()) {
putClientProperty("charset", charSetSpec);
} else {
setCharsetFromContentTypeParameters(charSetSpec);
}
try {
in.reset();
} catch (IOException exception) {
//mark was invalidated
in.close();
URL url = (URL)doc.getProperty(Document.StreamDescriptionProperty);
if (url != null) {
URLConnection conn = url.openConnection();
in = conn.getInputStream();
} else {
//there is nothing we can do to recover stream
throw changedCharSetException;
}
}
try {
doc.remove(0, doc.getLength());
} catch (BadLocationException e) {}
doc.putProperty("IgnoreCharsetDirective", Boolean.valueOf(true));
read(in, doc);
}
}
/**
* Loads a stream into the text document model.
*/
class PageLoader extends SwingWorkersetPage
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.
* EditorKit
to use for loading the stream.
* Document.StreamDescriptionProperty
so that relative
* URL's can be properly resolved.
*
* @param page the URL of the page
*/
protected InputStream getStream(URL page) throws IOException {
final URLConnection conn = page.openConnection();
if (conn instanceof HttpURLConnection) {
HttpURLConnection hconn = (HttpURLConnection) conn;
hconn.setInstanceFollowRedirects(false);
Object postData = getPostData();
if (postData != null) {
handlePostData(hconn, postData);
}
int response = hconn.getResponseCode();
boolean redirect = (response >= 300 && response <= 399);
/*
* In the case of a redirect, we want to actually change the URL
* that was input to the new, redirected URL
*/
if (redirect) {
String loc = conn.getHeaderField("Location");
if (loc.startsWith("http", 0)) {
page = new URL(loc);
} else {
page = new URL(page, loc);
}
return getStream(page);
}
}
// Connection properties handler should be forced to run on EDT,
// as it instantiates the EditorKit.
if (SwingUtilities.isEventDispatchThread()) {
handleConnectionProperties(conn);
} else {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
handleConnectionProperties(conn);
}
});
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
return conn.getInputStream();
}
/**
* Handle URL connection properties (most notably, content type).
*/
private void handleConnectionProperties(URLConnection conn) {
if (pageProperties == null) {
pageProperties = new HashtableUL.getRef
* method for the URL being displayed). By default, this
* method only knows how to locate a reference in an
* HTMLDocument. The implementation calls the
* scrollRectToVisible
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.
*
* @param reference the named location to scroll to
*/
public void scrollToReference(String reference) {
Document d = getDocument();
if (d instanceof HTMLDocument) {
HTMLDocument doc = (HTMLDocument) d;
HTMLDocument.Iterator iter = doc.getIterator(HTML.Tag.A);
for (; iter.isValid(); iter.next()) {
AttributeSet a = iter.getAttributes();
String nm = (String) a.getAttribute(HTML.Attribute.NAME);
if ((nm != null) && nm.equals(reference)) {
// found a matching reference in the document.
try {
int pos = iter.getStartOffset();
Rectangle r = modelToView(pos);
if (r != null) {
// the view is visible, scroll it to the
// center of the current visible area.
Rectangle vis = getVisibleRect();
//r.y -= (vis.height / 2);
r.height = vis.height;
scrollRectToVisible(r);
setCaretPosition(pos);
}
} catch (BadLocationException ble) {
UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
}
}
}
}
}
/**
* Gets the current URL being displayed. If a URL was
* not specified in the creation of the document, this
* will return null
, and relative URL's will not be
* resolved.
*
* @return the URL, or null
if none
*/
public URL getPage() {
return (URL) getDocument().getProperty(Document.StreamDescriptionProperty);
}
/**
* Sets the current URL being displayed.
*
* @param url the URL for display
* @exception IOException for a null
or invalid URL
* specification
*/
public void setPage(String url) throws IOException {
if (url == null) {
throw new IOException("invalid url");
}
URL page = new URL(url);
setPage(page);
}
/**
* Gets the class ID for the UI.
*
* @return the string "EditorPaneUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/**
* Creates the default editor kit (PlainEditorKit
) for when
* the component is first created.
*
* @return the editor kit
*/
protected EditorKit createDefaultEditorKit() {
return new PlainEditorKit();
}
/**
* Fetches the currently installed kit for handling content.
* createDefaultEditorKit
is called to set up a default
* if necessary.
*
* @return the editor kit
*/
public EditorKit getEditorKit() {
if (kit == null) {
kit = createDefaultEditorKit();
isUserSetEditorKit = false;
}
return kit;
}
/**
* 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 installed EditorKit
.
*
* @return the content type, null
if no editor kit set
*/
public final String getContentType() {
return (kit != null) ? kit.getContentType() : null;
}
/**
* Sets the type of content that this editor
* handles. This calls getEditorKitForContentType
,
* and then setEditorKit
if an editor kit can
* be successfully located. This is mostly convenience method
* that can be used as an alternative to calling
* setEditorKit
directly.
* EditorKit
.
* For example if the type is specified as
* text/html; charset=EUC-JP
the content
* will be loaded using the EditorKit
registered for
* text/html
and the Reader provided to
* the EditorKit
to load unicode into the document will
* use the EUC-JP
charset for translating
* to unicode. If the type is not recognized, the content
* will be loaded using the EditorKit
registered
* for plain text, text/plain
.
*
* @param type the non-null
mime type for the content editing
* support
* @see #getContentType
* @beaninfo
* description: the type of content
* @throws NullPointerException if the type
parameter
* is null
*/
public final void setContentType(String type) {
// The type could have optional info is part of it,
// for example some charset info. We need to strip that
// of and save it.
int parm = type.indexOf(";");
if (parm > -1) {
// Save the paramList.
String paramList = type.substring(parm);
// update the content type string.
type = type.substring(0, parm).trim();
if (type.toLowerCase().startsWith("text/")) {
setCharsetFromContentTypeParameters(paramList);
}
}
if ((kit == null) || (! type.equals(kit.getContentType()))
|| !isUserSetEditorKit) {
EditorKit k = getEditorKitForContentType(type);
if (k != null && k != kit) {
setEditorKit(k);
isUserSetEditorKit = false;
}
}
}
/**
* This method gets the charset information specified as part
* of the content type in the http header information.
*/
private void setCharsetFromContentTypeParameters(String paramlist) {
String charset;
try {
// paramlist is handed to us with a leading ';', strip it.
int semi = paramlist.indexOf(';');
if (semi > -1 && semi < paramlist.length()-1) {
paramlist = paramlist.substring(semi + 1);
}
if (paramlist.length() > 0) {
// parse the paramlist into attr-value pairs & get the
// charset pair's value
HeaderParser hdrParser = new HeaderParser(paramlist);
charset = hdrParser.findValue("charset");
if (charset != null) {
putClientProperty("charset", charset);
}
}
}
catch (IndexOutOfBoundsException e) {
// malformed parameter list, use charset we have
}
catch (NullPointerException e) {
// malformed parameter list, use charset we have
}
catch (Exception e) {
// malformed parameter list, use charset we have; but complain
System.err.println("JEditorPane.getCharsetFromContentTypeParameters failed on: " + paramlist);
e.printStackTrace();
}
}
/**
* 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.
* A PropertyChange
event ("editorKit") is always fired when
* setEditorKit
is called.
* EditorKit
is the source of how a
* particular type
* of content is modeled. This method will cause setDocument
* to be called on behalf of the caller to ensure integrity
* of the internal state.
*
* @param kit the desired editor behavior
* @see #getEditorKit
* @beaninfo
* description: the currently installed kit for handling content
* bound: true
* expert: true
*/
public void setEditorKit(EditorKit kit) {
EditorKit old = this.kit;
isUserSetEditorKit = true;
if (old != null) {
old.deinstall(this);
}
this.kit = kit;
if (this.kit != null) {
this.kit.install(this);
setDocument(this.kit.createDefaultDocument());
}
firePropertyChange("editorKit", old, kit);
}
/**
* 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 an EditorKit
registered
* for the given type, it will try to create an
* EditorKit
from the default EditorKit
registry.
* If that fails, a PlainEditorKit
is used on the
* assumption that all text documents can be represented
* as plain text.
* null
content type
* @return the editor kit
*/
public EditorKit getEditorKitForContentType(String type) {
if (typeHandlers == null) {
typeHandlers = new HashtablecreateEditorKitForContentType
to install handlers for
* content types with a look-and-feel bias.
*
* @param type the non-null
content type
* @param k the editor kit to be set
*/
public void setEditorKitForContentType(String type, EditorKit k) {
if (typeHandlers == null) {
typeHandlers = new Hashtablenull
) 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.
*
* @param content the content to replace the selection with. This
* value can be null
*/
@Override
public void replaceSelection(String content) {
if (! isEditable()) {
UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
return;
}
EditorKit kit = getEditorKit();
if(kit instanceof StyledEditorKit) {
try {
Document doc = getDocument();
Caret caret = getCaret();
boolean composedTextSaved = saveComposedText(caret.getDot());
int p0 = Math.min(caret.getDot(), caret.getMark());
int p1 = Math.max(caret.getDot(), caret.getMark());
if (doc instanceof AbstractDocument) {
((AbstractDocument)doc).replace(p0, p1 - p0, content,
((StyledEditorKit)kit).getInputAttributes());
}
else {
if (p0 != p1) {
doc.remove(p0, p1 - p0);
}
if (content != null && content.length() > 0) {
doc.insertString(p0, content, ((StyledEditorKit)kit).
getInputAttributes());
}
}
if (composedTextSaved) {
restoreComposedText();
}
} catch (BadLocationException e) {
UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
}
}
else {
super.replaceSelection(content);
}
}
/**
* 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 a ClassLoader
,
* that ClassLoader
will be used to load the prototype.
* If there was no registered ClassLoader
,
* Class.forName
will be used to load the prototype.
* EditorKit
instance is successfully
* located, it is cloned and the clone is returned.
*
* @param type the content type
* @return the editor kit, or null
if there is nothing
* registered for the given type
*/
public static EditorKit createEditorKitForContentType(String type) {
Hashtabletype
to
* classname
.
* The class will be dynamically loaded later when actually
* needed, and can be safely changed before attempted uses
* to avoid loading unwanted classes. The prototype
* EditorKit
will be loaded with Class.forName
* when registered with this method.
*
* @param type the non-null
content type
* @param classname the class to load later
*/
public static void registerEditorKitForContentType(String type, String classname) {
registerEditorKitForContentType(type, classname,Thread.currentThread().
getContextClassLoader());
}
/**
* Establishes the default bindings of type
to
* classname
.
* The class will be dynamically loaded later when actually
* needed using the given ClassLoader
,
* and can be safely changed
* before attempted uses to avoid loading unwanted classes.
*
* @param type the non-null
content type
* @param classname the class to load later
* @param loader the ClassLoader
to use to load the name
*/
public static void registerEditorKitForContentType(String type, String classname, ClassLoader loader) {
getKitTypeRegistry().put(type, classname);
if (loader != null) {
getKitLoaderRegistry().put(type, loader);
} else {
getKitLoaderRegistry().remove(type);
}
getKitRegisty().remove(type);
}
/**
* Returns the currently registered EditorKit
* class name for the type type
.
*
* @param type the non-null
content type
*
* @since 1.3
*/
public static String getEditorKitClassNameForContentType(String type) {
return getKitTypeRegistry().get(type);
}
private static HashtableJEditorPane
.
* The preferred size for JEditorPane
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.
*
* @return a Dimension
containing the preferred size
*/
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
Container parent = SwingUtilities.getUnwrappedParent(this);
if (parent instanceof JViewport) {
JViewport port = (JViewport) parent;
TextUI ui = getUI();
int prefWidth = d.width;
int prefHeight = d.height;
if (! getScrollableTracksViewportWidth()) {
int w = port.getWidth();
Dimension min = ui.getMinimumSize(this);
if (w != 0 && w < min.width) {
// Only adjust to min if we have a valid size
prefWidth = min.width;
}
}
if (! getScrollableTracksViewportHeight()) {
int h = port.getHeight();
Dimension min = ui.getMinimumSize(this);
if (h != 0 && h < min.height) {
// Only adjust to min if we have a valid size
prefHeight = min.height;
}
}
if (prefWidth != d.width || prefHeight != d.height) {
d = new Dimension(prefWidth, prefHeight);
}
}
return d;
}
// --- JTextComponent methods -----------------------------
/**
* Sets the text of this TextComponent
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 to text/html
* the string should be specified in terms of HTML.
* 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
* existing Document
with the new one. You are then assured the
* previous Document
won't have any lingering state.
*
*
* null
the old
* text will be deleted
* @see #getText
* @beaninfo
* description: the text of this component
*/
public void setText(String t) {
try {
Document doc = getDocument();
doc.remove(0, doc.getLength());
if (t == null || t.equals("")) {
return;
}
Reader r = new StringReader(t);
EditorKit kit = getEditorKit();
kit.read(r, doc, 0);
} catch (IOException ioe) {
UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
} catch (BadLocationException ble) {
UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this);
}
}
/**
* Returns the text contained in this TextComponent
* 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 call JTextComponent.write
with
* a StringWriter
.
*
* @return the text
* @see #setText
*/
public String getText() {
String txt;
try {
StringWriter buf = new StringWriter();
write(buf);
txt = buf.toString();
} catch (IOException ioe) {
txt = null;
}
return txt;
}
// --- Scrollable ----------------------------------------
/**
* Returns true if a viewport should always force the width of this
* Scrollable
to match the width of the viewport.
*
* @return true if a viewport should force the Scrollables width to
* match its own, false otherwise
*/
public boolean getScrollableTracksViewportWidth() {
Container parent = SwingUtilities.getUnwrappedParent(this);
if (parent instanceof JViewport) {
JViewport port = (JViewport) parent;
TextUI ui = getUI();
int w = port.getWidth();
Dimension min = ui.getMinimumSize(this);
Dimension max = ui.getMaximumSize(this);
if ((w >= min.width) && (w <= max.width)) {
return true;
}
}
return false;
}
/**
* Returns true if a viewport should always force the height of this
* Scrollable
to match the height of the viewport.
*
* @return true if a viewport should force the
* Scrollable
's height to match its own,
* false otherwise
*/
public boolean getScrollableTracksViewportHeight() {
Container parent = SwingUtilities.getUnwrappedParent(this);
if (parent instanceof JViewport) {
JViewport port = (JViewport) parent;
TextUI ui = getUI();
int h = port.getHeight();
Dimension min = ui.getMinimumSize(this);
if (h >= min.height) {
Dimension max = ui.getMaximumSize(this);
if (h <= max.height) {
return true;
}
}
}
return false;
}
// --- Serialization ------------------------------------
/**
* See readObject
and writeObject
in
* JComponent
for more
* information about serialization in Swing.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
// --- variables ---------------------------------------
private SwingWorkerBoolean.TRUE
.
*
* @since 1.5
*/
public static final String W3C_LENGTH_UNITS = "JEditorPane.w3cLengthUnits";
/**
* 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.
* Boolean.TRUE
.
*
* @since 1.5
*/
public static final String HONOR_DISPLAY_PROPERTIES = "JEditorPane.honorDisplayProperties";
static final MapJEditorPane
.
* 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
* be null
.
*
* @return a string representation of this JEditorPane
*/
protected String paramString() {
String kitString = (kit != null ?
kit.toString() : "");
String typeHandlersString = (typeHandlers != null ?
typeHandlers.toString() : "");
return super.paramString() +
",kit=" + kitString +
",typeHandlers=" + typeHandlersString;
}
/////////////////
// Accessibility support
////////////////
/**
* 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.
*
* @return an AccessibleJEditorPane that serves as the
* AccessibleContext of this JEditorPane
*/
public AccessibleContext getAccessibleContext() {
if (getEditorKit() instanceof HTMLEditorKit) {
if (accessibleContext == null || accessibleContext.getClass() !=
AccessibleJEditorPaneHTML.class) {
accessibleContext = new AccessibleJEditorPaneHTML();
}
} else if (accessibleContext == null || accessibleContext.getClass() !=
AccessibleJEditorPane.class) {
accessibleContext = new AccessibleJEditorPane();
}
return accessibleContext;
}
/**
* This class implements accessibility support for the
* JEditorPane
class. It provides an implementation of the
* Java Accessibility API appropriate to editor pane user-interface
* elements.
* java.beans
package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJEditorPane extends AccessibleJTextComponent {
/**
* Gets the accessibleDescription property of this object. If this
* property isn't set, returns the content type of this
* JEditorPane
instead (e.g. "plain/text", "html/text").
*
* @return the localized description of the object; null
* if this object does not have a description
*
* @see #setAccessibleName
*/
public String getAccessibleDescription() {
String description = accessibleDescription;
// fallback to client property
if (description == null) {
description = (String)getClientProperty(AccessibleContext.ACCESSIBLE_DESCRIPTION_PROPERTY);
}
if (description == null) {
description = JEditorPane.this.getContentType();
}
return description;
}
/**
* Gets the state set of this object.
*
* @return an instance of AccessibleStateSet describing the states
* of the object
* @see AccessibleStateSet
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
states.add(AccessibleState.MULTI_LINE);
return states;
}
}
/**
* This class provides support for AccessibleHypertext
,
* and is used in instances where the EditorKit
* installed in this JEditorPane
is an instance of
* HTMLEditorKit
.
* java.beans
package.
* Please see {@link java.beans.XMLEncoder}.
*/
protected class AccessibleJEditorPaneHTML extends AccessibleJEditorPane {
private AccessibleContext accessibleContext;
public AccessibleText getAccessibleText() {
return new JEditorPaneAccessibleHypertextSupport();
}
protected AccessibleJEditorPaneHTML () {
HTMLEditorKit kit = (HTMLEditorKit)JEditorPane.this.getEditorKit();
accessibleContext = kit.getAccessibleContext();
}
/**
* Returns the number of accessible children of the object.
*
* @return the number of accessible children of the object.
*/
public int getAccessibleChildrenCount() {
if (accessibleContext != null) {
return accessibleContext.getAccessibleChildrenCount();
} else {
return 0;
}
}
/**
* Returns the specified Accessible child of the object. The Accessible
* children of an Accessible object are zero-based, so the first child
* of an Accessible child is at index 0, the second child is at index 1,
* and so on.
*
* @param i zero-based index of child
* @return the Accessible child of the object
* @see #getAccessibleChildrenCount
*/
public Accessible getAccessibleChild(int i) {
if (accessibleContext != null) {
return accessibleContext.getAccessibleChild(i);
} else {
return null;
}
}
/**
* Returns the Accessible child, if one exists, contained at the local
* coordinate Point.
*
* @param p The point relative to the coordinate system of this object.
* @return the Accessible, if it exists, at the specified location;
* otherwise null
*/
public Accessible getAccessibleAt(Point p) {
if (accessibleContext != null && p != null) {
try {
AccessibleComponent acomp =
accessibleContext.getAccessibleComponent();
if (acomp != null) {
return acomp.getAccessibleAt(p);
} else {
return null;
}
} catch (IllegalComponentStateException e) {
return null;
}
} else {
return null;
}
}
}
/**
* What's returned by
* AccessibleJEditorPaneHTML.getAccessibleText
.
*
* Provides support for AccessibleHypertext
in case
* there is an HTML document being displayed in this
* JEditorPane
.
*
*/
protected class JEditorPaneAccessibleHypertextSupport
extends AccessibleJEditorPane implements AccessibleHypertext {
public class HTMLLink extends AccessibleHyperlink {
Element element;
public HTMLLink(Element e) {
element = e;
}
/**
* Since the document a link is associated with may have
* changed, this method returns whether this Link is valid
* anymore (with respect to the document it references).
*
* @return a flag indicating whether this link is still valid with
* respect to the AccessibleHypertext it belongs to
*/
public boolean isValid() {
return JEditorPaneAccessibleHypertextSupport.this.linksValid;
}
/**
* Returns the number of accessible actions available in this Link
* If there are more than one, the first one is NOT considered the
* "default" action of this LINK object (e.g. in an HTML imagemap).
* In general, links will have only one AccessibleAction in them.
*
* @return the zero-based number of Actions in this object
*/
public int getAccessibleActionCount() {
return 1;
}
/**
* Perform the specified Action on the object
*
* @param i zero-based index of actions
* @return true if the the action was performed; else false.
* @see #getAccessibleActionCount
*/
public boolean doAccessibleAction(int i) {
if (i == 0 && isValid() == true) {
URL u = (URL) getAccessibleActionObject(i);
if (u != null) {
HyperlinkEvent linkEvent =
new HyperlinkEvent(JEditorPane.this, HyperlinkEvent.EventType.ACTIVATED, u);
JEditorPane.this.fireHyperlinkUpdate(linkEvent);
return true;
}
}
return false; // link invalid or i != 0
}
/**
* Return a String description of this particular
* link action. The string returned is the text
* within the document associated with the element
* which contains this link.
*
* @param i zero-based index of the actions
* @return a String description of the action
* @see #getAccessibleActionCount
*/
public String getAccessibleActionDescription(int i) {
if (i == 0 && isValid() == true) {
Document d = JEditorPane.this.getDocument();
if (d != null) {
try {
return d.getText(getStartIndex(),
getEndIndex() - getStartIndex());
} catch (BadLocationException exception) {
return null;
}
}
}
return null;
}
/**
* Returns a URL object that represents the link.
*
* @param i zero-based index of the actions
* @return an URL representing the HTML link itself
* @see #getAccessibleActionCount
*/
public Object getAccessibleActionObject(int i) {
if (i == 0 && isValid() == true) {
AttributeSet as = element.getAttributes();
AttributeSet anchor =
(AttributeSet) as.getAttribute(HTML.Tag.A);
String href = (anchor != null) ?
(String) anchor.getAttribute(HTML.Attribute.HREF) : null;
if (href != null) {
URL u;
try {
u = new URL(JEditorPane.this.getPage(), href);
} catch (MalformedURLException m) {
u = null;
}
return u;
}
}
return null; // link invalid or i != 0
}
/**
* Return an object that represents the link anchor,
* as appropriate for that link. E.g. from HTML:
* Accessibility
* this method would return a String containing the text:
* 'Accessibility'.
*
* Similarly, from this HTML:
* <a HREF="#top"><img src="top-hat.gif" alt="top hat"></a>
* this might return the object ImageIcon("top-hat.gif", "top hat");
*
* @param i zero-based index of the actions
* @return an Object representing the hypertext anchor
* @see #getAccessibleActionCount
*/
public Object getAccessibleActionAnchor(int i) {
return getAccessibleActionDescription(i);
}
/**
* Get the index with the hypertext document at which this
* link begins
*
* @return index of start of link
*/
public int getStartIndex() {
return element.getStartOffset();
}
/**
* Get the index with the hypertext document at which this
* link ends
*
* @return index of end of link
*/
public int getEndIndex() {
return element.getEndOffset();
}
}
private class LinkVector extends Vector