0N/A/*
3909N/A * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/Apackage javax.swing.text;
0N/A
0N/Aimport java.lang.reflect.Method;
0N/A
0N/Aimport java.security.AccessController;
0N/Aimport java.security.PrivilegedAction;
0N/A
243N/Aimport java.beans.Transient;
0N/Aimport java.util.Collections;
0N/Aimport java.util.HashMap;
0N/Aimport java.util.Hashtable;
0N/Aimport java.util.Enumeration;
0N/Aimport java.util.Vector;
0N/Aimport java.util.Map;
0N/A
0N/Aimport java.util.concurrent.*;
0N/A
0N/Aimport java.io.*;
0N/A
0N/Aimport java.awt.*;
0N/Aimport java.awt.event.*;
0N/Aimport java.awt.print.*;
0N/Aimport java.awt.datatransfer.*;
0N/Aimport java.awt.im.InputContext;
0N/Aimport java.awt.im.InputMethodRequests;
0N/Aimport java.awt.font.TextHitInfo;
0N/Aimport java.awt.font.TextAttribute;
0N/A
0N/Aimport java.awt.print.Printable;
0N/Aimport java.awt.print.PrinterException;
0N/A
0N/Aimport javax.print.PrintService;
0N/Aimport javax.print.attribute.PrintRequestAttributeSet;
0N/A
0N/Aimport java.text.*;
0N/Aimport java.text.AttributedCharacterIterator.Attribute;
0N/A
0N/Aimport javax.swing.*;
0N/Aimport javax.swing.event.*;
0N/Aimport javax.swing.plaf.*;
0N/A
0N/Aimport javax.accessibility.*;
0N/A
0N/Aimport javax.print.attribute.*;
0N/A
0N/Aimport sun.awt.AppContext;
0N/A
0N/A
0N/Aimport sun.swing.PrintingStatus;
0N/Aimport sun.swing.SwingUtilities2;
0N/Aimport sun.swing.text.TextComponentPrintable;
1338N/Aimport sun.swing.SwingAccessor;
0N/A
0N/A/**
0N/A * <code>JTextComponent</code> is the base class for swing text
0N/A * components. It tries to be compatible with the
0N/A * <code>java.awt.TextComponent</code> class
0N/A * where it can reasonably do so. Also provided are other services
0N/A * for additional flexibility (beyond the pluggable UI and bean
0N/A * support).
0N/A * You can find information on how to use the functionality
0N/A * this class provides in
0N/A * <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html">General Rules for Using Text Components</a>,
0N/A * a section in <em>The Java Tutorial.</em>
0N/A *
0N/A * <p>
0N/A * <dl>
0N/A * <dt><b><font size=+1>Caret Changes</font></b>
0N/A * <dd>
0N/A * The caret is a pluggable object in swing text components.
0N/A * Notification of changes to the caret position and the selection
0N/A * are sent to implementations of the <code>CaretListener</code>
0N/A * interface that have been registered with the text component.
0N/A * The UI will install a default caret unless a customized caret
0N/A * has been set. <br>
0N/A * By default the caret tracks all the document changes
0N/A * performed on the Event Dispatching Thread and updates it's position
0N/A * accordingly if an insertion occurs before or at the caret position
0N/A * or a removal occurs before the caret position. <code>DefaultCaret</code>
0N/A * tries to make itself visible which may lead to scrolling
0N/A * of a text component within <code>JScrollPane</code>. The default caret
0N/A * behavior can be changed by the {@link DefaultCaret#setUpdatePolicy} method.
0N/A * <br>
0N/A * <b>Note</b>: Non-editable text components also have a caret though
0N/A * it may not be painted.
0N/A *
0N/A * <p>
0N/A * <dt><b><font size=+1>Commands</font></b>
0N/A * <dd>
0N/A * Text components provide a number of commands that can be used
0N/A * to manipulate the component. This is essentially the way that
0N/A * the component expresses its capabilities. These are expressed
0N/A * in terms of the swing <code>Action</code> interface,
0N/A * using the <code>TextAction</code> implementation.
0N/A * The set of commands supported by the text component can be
0N/A * found with the {@link #getActions} method. These actions
0N/A * can be bound to key events, fired from buttons, etc.
0N/A *
0N/A * <p>
0N/A * <dt><b><font size=+1>Text Input</font></b>
0N/A * <dd>
0N/A * The text components support flexible and internationalized text input, using
0N/A * keymaps and the input method framework, while maintaining compatibility with
0N/A * the AWT listener model.
0N/A * <p>
0N/A * A {@link javax.swing.text.Keymap} lets an application bind key
0N/A * strokes to actions.
0N/A * In order to allow keymaps to be shared across multiple text components, they
0N/A * can use actions that extend <code>TextAction</code>.
0N/A * <code>TextAction</code> can determine which <code>JTextComponent</code>
0N/A * most recently has or had focus and therefore is the subject of
0N/A * the action (In the case that the <code>ActionEvent</code>
0N/A * sent to the action doesn't contain the target text component as its source).
0N/A * <p>
0N/A * The <a href="../../../../technotes/guides/imf/spec.html">input method framework</a>
0N/A * lets text components interact with input methods, separate software
0N/A * components that preprocess events to let users enter thousands of
0N/A * different characters using keyboards with far fewer keys.
0N/A * <code>JTextComponent</code> is an <em>active client</em> of
0N/A * the framework, so it implements the preferred user interface for interacting
0N/A * with input methods. As a consequence, some key events do not reach the text
0N/A * component because they are handled by an input method, and some text input
0N/A * reaches the text component as committed text within an {@link
0N/A * java.awt.event.InputMethodEvent} instead of as a key event.
0N/A * The complete text input is the combination of the characters in
0N/A * <code>keyTyped</code> key events and committed text in input method events.
0N/A * <p>
0N/A * The AWT listener model lets applications attach event listeners to
0N/A * components in order to bind events to actions. Swing encourages the
0N/A * use of keymaps instead of listeners, but maintains compatibility
0N/A * with listeners by giving the listeners a chance to steal an event
0N/A * by consuming it.
0N/A * <p>
0N/A * Keyboard event and input method events are handled in the following stages,
0N/A * with each stage capable of consuming the event:
0N/A *
0N/A * <table border=1 summary="Stages of keyboard and input method event handling">
0N/A * <tr>
0N/A * <th id="stage"><p align="left">Stage</p></th>
0N/A * <th id="ke"><p align="left">KeyEvent</p></th>
0N/A * <th id="ime"><p align="left">InputMethodEvent</p></th></tr>
0N/A * <tr><td headers="stage">1. </td>
0N/A * <td headers="ke">input methods </td>
0N/A * <td headers="ime">(generated here)</td></tr>
0N/A * <tr><td headers="stage">2. </td>
0N/A * <td headers="ke">focus manager </td>
0N/A * <td headers="ime"></td>
0N/A * </tr>
0N/A * <tr>
0N/A * <td headers="stage">3. </td>
0N/A * <td headers="ke">registered key listeners</td>
0N/A * <td headers="ime">registered input method listeners</tr>
0N/A * <tr>
0N/A * <td headers="stage">4. </td>
0N/A * <td headers="ke"></td>
0N/A * <td headers="ime">input method handling in JTextComponent</tr>
0N/A * <tr>
0N/A * <td headers="stage">5. </td><td headers="ke ime" colspan=2>keymap handling using the current keymap</td></tr>
0N/A * <tr><td headers="stage">6. </td><td headers="ke">keyboard handling in JComponent (e.g. accelerators, component navigation, etc.)</td>
0N/A * <td headers="ime"></td></tr>
0N/A * </table>
0N/A *
0N/A * <p>
0N/A * To maintain compatibility with applications that listen to key
0N/A * events but are not aware of input method events, the input
0N/A * method handling in stage 4 provides a compatibility mode for
0N/A * components that do not process input method events. For these
0N/A * components, the committed text is converted to keyTyped key events
0N/A * and processed in the key event pipeline starting at stage 3
0N/A * instead of in the input method event pipeline.
0N/A * <p>
0N/A * By default the component will create a keymap (named <b>DEFAULT_KEYMAP</b>)
0N/A * that is shared by all JTextComponent instances as the default keymap.
0N/A * Typically a look-and-feel implementation will install a different keymap
0N/A * that resolves to the default keymap for those bindings not found in the
0N/A * different keymap. The minimal bindings include:
0N/A * <ul>
0N/A * <li>inserting content into the editor for the
0N/A * printable keys.
0N/A * <li>removing content with the backspace and del
0N/A * keys.
0N/A * <li>caret movement forward and backward
0N/A * </ul>
0N/A *
0N/A * <p>
0N/A * <dt><b><font size=+1>Model/View Split</font></b>
0N/A * <dd>
0N/A * The text components have a model-view split. A text component pulls
0N/A * together the objects used to represent the model, view, and controller.
0N/A * The text document model may be shared by other views which act as observers
0N/A * of the model (e.g. a document may be shared by multiple components).
0N/A *
0N/A * <p align=center><img src="doc-files/editor.gif" alt="Diagram showing interaction between Controller, Document, events, and ViewFactory"
0N/A * HEIGHT=358 WIDTH=587></p>
0N/A *
0N/A * <p>
0N/A * The model is defined by the {@link Document} interface.
0N/A * This is intended to provide a flexible text storage mechanism
0N/A * that tracks change during edits and can be extended to more sophisticated
0N/A * models. The model interfaces are meant to capture the capabilities of
0N/A * expression given by SGML, a system used to express a wide variety of
0N/A * content.
0N/A * Each modification to the document causes notification of the
0N/A * details of the change to be sent to all observers in the form of a
0N/A * {@link DocumentEvent} which allows the views to stay up to date with the model.
0N/A * This event is sent to observers that have implemented the
0N/A * {@link DocumentListener}
0N/A * interface and registered interest with the model being observed.
0N/A *
0N/A * <p>
0N/A * <dt><b><font size=+1>Location Information</font></b>
0N/A * <dd>
0N/A * The capability of determining the location of text in
0N/A * the view is provided. There are two methods, {@link #modelToView}
0N/A * and {@link #viewToModel} for determining this information.
0N/A *
0N/A * <p>
0N/A * <dt><b><font size=+1>Undo/Redo support</font></b>
0N/A * <dd>
0N/A * Support for an edit history mechanism is provided to allow
0N/A * undo/redo operations. The text component does not itself
0N/A * provide the history buffer by default, but does provide
0N/A * the <code>UndoableEdit</code> records that can be used in conjunction
0N/A * with a history buffer to provide the undo/redo support.
0N/A * The support is provided by the Document model, which allows
0N/A * one to attach UndoableEditListener implementations.
0N/A *
0N/A * <p>
0N/A * <dt><b><font size=+1>Thread Safety</font></b>
0N/A * <dd>
0N/A * The swing text components provide some support of thread
0N/A * safe operations. Because of the high level of configurability
0N/A * of the text components, it is possible to circumvent the
0N/A * protection provided. The protection primarily comes from
0N/A * the model, so the documentation of <code>AbstractDocument</code>
0N/A * describes the assumptions of the protection provided.
0N/A * The methods that are safe to call asynchronously are marked
0N/A * with comments.
0N/A *
0N/A * <p>
0N/A * <dt><b><font size=+1>Newlines</font></b>
0N/A * <dd>
0N/A * For a discussion on how newlines are handled, see
0N/A * <a href="DefaultEditorKit.html">DefaultEditorKit</a>.
0N/A *
0N/A * <p>
0N/A * <dt><b><font size=+1>Printing support</font></b>
0N/A * <dd>
0N/A * Several {@link #print print} methods are provided for basic
0N/A * document printing. If more advanced printing is needed, use the
0N/A * {@link #getPrintable} method.
0N/A * </dl>
0N/A *
0N/A * <p>
0N/A * <strong>Warning:</strong>
0N/A * Serialized objects of this class will not be compatible with
0N/A * future Swing releases. The current serialization support is
0N/A * appropriate for short term storage or RMI between applications running
0N/A * the same version of Swing. As of 1.4, support for long term storage
0N/A * of all JavaBeans<sup><font size="-2">TM</font></sup>
0N/A * has been added to the <code>java.beans</code> package.
0N/A * Please see {@link java.beans.XMLEncoder}.
0N/A *
0N/A * @beaninfo
0N/A * attribute: isContainer false
0N/A *
0N/A * @author Timothy Prinzing
0N/A * @author Igor Kushnirskiy (printing support)
0N/A * @see Document
0N/A * @see DocumentEvent
0N/A * @see DocumentListener
0N/A * @see Caret
0N/A * @see CaretEvent
0N/A * @see CaretListener
0N/A * @see TextUI
0N/A * @see View
0N/A * @see ViewFactory
0N/A */
0N/Apublic abstract class JTextComponent extends JComponent implements Scrollable, Accessible
0N/A{
0N/A /**
0N/A * Creates a new <code>JTextComponent</code>.
0N/A * Listeners for caret events are established, and the pluggable
0N/A * UI installed. The component is marked as editable. No layout manager
0N/A * is used, because layout is managed by the view subsystem of text.
0N/A * The document model is set to <code>null</code>.
0N/A */
0N/A public JTextComponent() {
0N/A super();
0N/A // enable InputMethodEvent for on-the-spot pre-editing
0N/A enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.INPUT_METHOD_EVENT_MASK);
0N/A caretEvent = new MutableCaretEvent(this);
0N/A addMouseListener(caretEvent);
0N/A addFocusListener(caretEvent);
0N/A setEditable(true);
0N/A setDragEnabled(false);
0N/A setLayout(null); // layout is managed by View hierarchy
0N/A updateUI();
0N/A }
0N/A
0N/A /**
0N/A * Fetches the user-interface factory for this text-oriented editor.
0N/A *
0N/A * @return the factory
0N/A */
0N/A public TextUI getUI() { return (TextUI)ui; }
0N/A
0N/A /**
0N/A * Sets the user-interface factory for this text-oriented editor.
0N/A *
0N/A * @param ui the factory
0N/A */
0N/A public void setUI(TextUI ui) {
0N/A super.setUI(ui);
0N/A }
0N/A
0N/A /**
0N/A * Reloads the pluggable UI. The key used to fetch the
0N/A * new interface is <code>getUIClassID()</code>. The type of
0N/A * the UI is <code>TextUI</code>. <code>invalidate</code>
0N/A * is called after setting the UI.
0N/A */
0N/A public void updateUI() {
0N/A setUI((TextUI)UIManager.getUI(this));
0N/A invalidate();
0N/A }
0N/A
0N/A /**
0N/A * Adds a caret listener for notification of any changes
0N/A * to the caret.
0N/A *
0N/A * @param listener the listener to be added
0N/A * @see javax.swing.event.CaretEvent
0N/A */
0N/A public void addCaretListener(CaretListener listener) {
0N/A listenerList.add(CaretListener.class, listener);
0N/A }
0N/A
0N/A /**
0N/A * Removes a caret listener.
0N/A *
0N/A * @param listener the listener to be removed
0N/A * @see javax.swing.event.CaretEvent
0N/A */
0N/A public void removeCaretListener(CaretListener listener) {
0N/A listenerList.remove(CaretListener.class, listener);
0N/A }
0N/A
0N/A /**
0N/A * Returns an array of all the caret listeners
0N/A * registered on this text component.
0N/A *
0N/A * @return all of this component's <code>CaretListener</code>s
0N/A * or an empty
0N/A * array if no caret listeners are currently registered
0N/A *
0N/A * @see #addCaretListener
0N/A * @see #removeCaretListener
0N/A *
0N/A * @since 1.4
0N/A */
0N/A public CaretListener[] getCaretListeners() {
611N/A return listenerList.getListeners(CaretListener.class);
0N/A }
0N/A
0N/A /**
0N/A * Notifies all listeners that have registered interest for
0N/A * notification on this event type. The event instance
0N/A * is lazily created using the parameters passed into
0N/A * the fire method. The listener list is processed in a
0N/A * last-to-first manner.
0N/A *
0N/A * @param e the event
0N/A * @see EventListenerList
0N/A */
0N/A protected void fireCaretUpdate(CaretEvent e) {
0N/A // Guaranteed to return a non-null array
0N/A Object[] listeners = listenerList.getListenerList();
0N/A // Process the listeners last to first, notifying
0N/A // those that are interested in this event
0N/A for (int i = listeners.length-2; i>=0; i-=2) {
0N/A if (listeners[i]==CaretListener.class) {
0N/A ((CaretListener)listeners[i+1]).caretUpdate(e);
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Associates the editor with a text document.
0N/A * The currently registered factory is used to build a view for
0N/A * the document, which gets displayed by the editor after revalidation.
0N/A * A PropertyChange event ("document") is propagated to each listener.
0N/A *
0N/A * @param doc the document to display/edit
0N/A * @see #getDocument
0N/A * @beaninfo
0N/A * description: the text document model
0N/A * bound: true
0N/A * expert: true
0N/A */
0N/A public void setDocument(Document doc) {
0N/A Document old = model;
0N/A
0N/A /*
0N/A * aquire a read lock on the old model to prevent notification of
0N/A * mutations while we disconnecting the old model.
0N/A */
0N/A try {
0N/A if (old instanceof AbstractDocument) {
0N/A ((AbstractDocument)old).readLock();
0N/A }
0N/A if (accessibleContext != null) {
0N/A model.removeDocumentListener(
0N/A ((AccessibleJTextComponent)accessibleContext));
0N/A }
0N/A if (inputMethodRequestsHandler != null) {
0N/A model.removeDocumentListener((DocumentListener)inputMethodRequestsHandler);
0N/A }
0N/A model = doc;
0N/A
0N/A // Set the document's run direction property to match the
0N/A // component's ComponentOrientation property.
0N/A Boolean runDir = getComponentOrientation().isLeftToRight()
0N/A ? TextAttribute.RUN_DIRECTION_LTR
0N/A : TextAttribute.RUN_DIRECTION_RTL;
0N/A if (runDir != doc.getProperty(TextAttribute.RUN_DIRECTION)) {
0N/A doc.putProperty(TextAttribute.RUN_DIRECTION, runDir );
0N/A }
0N/A firePropertyChange("document", old, doc);
0N/A } finally {
0N/A if (old instanceof AbstractDocument) {
0N/A ((AbstractDocument)old).readUnlock();
0N/A }
0N/A }
0N/A
0N/A revalidate();
0N/A repaint();
0N/A if (accessibleContext != null) {
0N/A model.addDocumentListener(
0N/A ((AccessibleJTextComponent)accessibleContext));
0N/A }
0N/A if (inputMethodRequestsHandler != null) {
0N/A model.addDocumentListener((DocumentListener)inputMethodRequestsHandler);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Fetches the model associated with the editor. This is
0N/A * primarily for the UI to get at the minimal amount of
0N/A * state required to be a text editor. Subclasses will
0N/A * return the actual type of the model which will typically
0N/A * be something that extends Document.
0N/A *
0N/A * @return the model
0N/A */
0N/A public Document getDocument() {
0N/A return model;
0N/A }
0N/A
0N/A // Override of Component.setComponentOrientation
0N/A public void setComponentOrientation( ComponentOrientation o ) {
0N/A // Set the document's run direction property to match the
0N/A // ComponentOrientation property.
0N/A Document doc = getDocument();
0N/A if( doc != null ) {
0N/A Boolean runDir = o.isLeftToRight()
0N/A ? TextAttribute.RUN_DIRECTION_LTR
0N/A : TextAttribute.RUN_DIRECTION_RTL;
0N/A doc.putProperty( TextAttribute.RUN_DIRECTION, runDir );
0N/A }
0N/A super.setComponentOrientation( o );
0N/A }
0N/A
0N/A /**
0N/A * Fetches the command list for the editor. This is
0N/A * the list of commands supported by the plugged-in UI
0N/A * augmented by the collection of commands that the
0N/A * editor itself supports. These are useful for binding
0N/A * to events, such as in a keymap.
0N/A *
0N/A * @return the command list
0N/A */
0N/A public Action[] getActions() {
0N/A return getUI().getEditorKit(this).getActions();
0N/A }
0N/A
0N/A /**
0N/A * Sets margin space between the text component's border
0N/A * and its text. The text component's default <code>Border</code>
0N/A * object will use this value to create the proper margin.
0N/A * However, if a non-default border is set on the text component,
0N/A * it is that <code>Border</code> object's responsibility to create the
0N/A * appropriate margin space (else this property will effectively
0N/A * be ignored). This causes a redraw of the component.
0N/A * A PropertyChange event ("margin") is sent to all listeners.
0N/A *
0N/A * @param m the space between the border and the text
0N/A * @beaninfo
0N/A * description: desired space between the border and text area
0N/A * bound: true
0N/A */
0N/A public void setMargin(Insets m) {
0N/A Insets old = margin;
0N/A margin = m;
0N/A firePropertyChange("margin", old, m);
0N/A invalidate();
0N/A }
0N/A
0N/A /**
0N/A * Returns the margin between the text component's border and
0N/A * its text.
0N/A *
0N/A * @return the margin
0N/A */
0N/A public Insets getMargin() {
0N/A return margin;
0N/A }
0N/A
0N/A /**
0N/A * Sets the <code>NavigationFilter</code>. <code>NavigationFilter</code>
0N/A * is used by <code>DefaultCaret</code> and the default cursor movement
0N/A * actions as a way to restrict the cursor movement.
0N/A *
0N/A * @since 1.4
0N/A */
0N/A public void setNavigationFilter(NavigationFilter filter) {
0N/A navigationFilter = filter;
0N/A }
0N/A
0N/A /**
0N/A * Returns the <code>NavigationFilter</code>. <code>NavigationFilter</code>
0N/A * is used by <code>DefaultCaret</code> and the default cursor movement
0N/A * actions as a way to restrict the cursor movement. A null return value
0N/A * implies the cursor movement and selection should not be restricted.
0N/A *
0N/A * @since 1.4
0N/A * @return the NavigationFilter
0N/A */
0N/A public NavigationFilter getNavigationFilter() {
0N/A return navigationFilter;
0N/A }
0N/A
0N/A /**
0N/A * Fetches the caret that allows text-oriented navigation over
0N/A * the view.
0N/A *
0N/A * @return the caret
0N/A */
243N/A @Transient
0N/A public Caret getCaret() {
0N/A return caret;
0N/A }
0N/A
0N/A /**
0N/A * Sets the caret to be used. By default this will be set
0N/A * by the UI that gets installed. This can be changed to
0N/A * a custom caret if desired. Setting the caret results in a
0N/A * PropertyChange event ("caret") being fired.
0N/A *
0N/A * @param c the caret
0N/A * @see #getCaret
0N/A * @beaninfo
0N/A * description: the caret used to select/navigate
0N/A * bound: true
0N/A * expert: true
0N/A */
0N/A public void setCaret(Caret c) {
0N/A if (caret != null) {
0N/A caret.removeChangeListener(caretEvent);
0N/A caret.deinstall(this);
0N/A }
0N/A Caret old = caret;
0N/A caret = c;
0N/A if (caret != null) {
0N/A caret.install(this);
0N/A caret.addChangeListener(caretEvent);
0N/A }
0N/A firePropertyChange("caret", old, caret);
0N/A }
0N/A
0N/A /**
0N/A * Fetches the object responsible for making highlights.
0N/A *
0N/A * @return the highlighter
0N/A */
0N/A public Highlighter getHighlighter() {
0N/A return highlighter;
0N/A }
0N/A
0N/A /**
0N/A * Sets the highlighter to be used. By default this will be set
0N/A * by the UI that gets installed. This can be changed to
0N/A * a custom highlighter if desired. The highlighter can be set to
0N/A * <code>null</code> to disable it.
0N/A * A PropertyChange event ("highlighter") is fired
0N/A * when a new highlighter is installed.
0N/A *
0N/A * @param h the highlighter
0N/A * @see #getHighlighter
0N/A * @beaninfo
0N/A * description: object responsible for background highlights
0N/A * bound: true
0N/A * expert: true
0N/A */
0N/A public void setHighlighter(Highlighter h) {
0N/A if (highlighter != null) {
0N/A highlighter.deinstall(this);
0N/A }
0N/A Highlighter old = highlighter;
0N/A highlighter = h;
0N/A if (highlighter != null) {
0N/A highlighter.install(this);
0N/A }
0N/A firePropertyChange("highlighter", old, h);
0N/A }
0N/A
0N/A /**
0N/A * Sets the keymap to use for binding events to
0N/A * actions. Setting to <code>null</code> effectively disables
0N/A * keyboard input.
0N/A * A PropertyChange event ("keymap") is fired when a new keymap
0N/A * is installed.
0N/A *
0N/A * @param map the keymap
0N/A * @see #getKeymap
0N/A * @beaninfo
0N/A * description: set of key event to action bindings to use
0N/A * bound: true
0N/A */
0N/A public void setKeymap(Keymap map) {
0N/A Keymap old = keymap;
0N/A keymap = map;
0N/A firePropertyChange("keymap", old, keymap);
0N/A updateInputMap(old, map);
0N/A }
0N/A
0N/A /**
0N/A * Turns on or off automatic drag handling. In order to enable automatic
0N/A * drag handling, this property should be set to {@code true}, and the
0N/A * component's {@code TransferHandler} needs to be {@code non-null}.
0N/A * The default value of the {@code dragEnabled} property is {@code false}.
0N/A * <p>
0N/A * The job of honoring this property, and recognizing a user drag gesture,
0N/A * lies with the look and feel implementation, and in particular, the component's
0N/A * {@code TextUI}. When automatic drag handling is enabled, most look and
0N/A * feels (including those that subclass {@code BasicLookAndFeel}) begin a
0N/A * drag and drop operation whenever the user presses the mouse button over
0N/A * a selection and then moves the mouse a few pixels. Setting this property to
0N/A * {@code true} can therefore have a subtle effect on how selections behave.
0N/A * <p>
0N/A * If a look and feel is used that ignores this property, you can still
0N/A * begin a drag and drop operation by calling {@code exportAsDrag} on the
0N/A * component's {@code TransferHandler}.
0N/A *
0N/A * @param b whether or not to enable automatic drag handling
0N/A * @exception HeadlessException if
0N/A * <code>b</code> is <code>true</code> and
0N/A * <code>GraphicsEnvironment.isHeadless()</code>
0N/A * returns <code>true</code>
0N/A * @see java.awt.GraphicsEnvironment#isHeadless
0N/A * @see #getDragEnabled
0N/A * @see #setTransferHandler
0N/A * @see TransferHandler
0N/A * @since 1.4
0N/A *
0N/A * @beaninfo
0N/A * description: determines whether automatic drag handling is enabled
0N/A * bound: false
0N/A */
0N/A public void setDragEnabled(boolean b) {
0N/A if (b && GraphicsEnvironment.isHeadless()) {
0N/A throw new HeadlessException();
0N/A }
0N/A dragEnabled = b;
0N/A }
0N/A
0N/A /**
0N/A * Returns whether or not automatic drag handling is enabled.
0N/A *
0N/A * @return the value of the {@code dragEnabled} property
0N/A * @see #setDragEnabled
0N/A * @since 1.4
0N/A */
0N/A public boolean getDragEnabled() {
0N/A return dragEnabled;
0N/A }
0N/A
0N/A /**
0N/A * Sets the drop mode for this component. For backward compatibility,
0N/A * the default for this property is <code>DropMode.USE_SELECTION</code>.
0N/A * Usage of <code>DropMode.INSERT</code> is recommended, however,
0N/A * for an improved user experience. It offers similar behavior of dropping
0N/A * between text locations, but does so without affecting the actual text
0N/A * selection and caret location.
0N/A * <p>
0N/A * <code>JTextComponents</code> support the following drop modes:
0N/A * <ul>
0N/A * <li><code>DropMode.USE_SELECTION</code></li>
0N/A * <li><code>DropMode.INSERT</code></li>
0N/A * </ul>
0N/A * <p>
0N/A * The drop mode is only meaningful if this component has a
0N/A * <code>TransferHandler</code> that accepts drops.
0N/A *
0N/A * @param dropMode the drop mode to use
0N/A * @throws IllegalArgumentException if the drop mode is unsupported
0N/A * or <code>null</code>
0N/A * @see #getDropMode
0N/A * @see #getDropLocation
0N/A * @see #setTransferHandler
0N/A * @see javax.swing.TransferHandler
0N/A * @since 1.6
0N/A */
0N/A public final void setDropMode(DropMode dropMode) {
0N/A if (dropMode != null) {
0N/A switch (dropMode) {
0N/A case USE_SELECTION:
0N/A case INSERT:
0N/A this.dropMode = dropMode;
0N/A return;
0N/A }
0N/A }
0N/A
0N/A throw new IllegalArgumentException(dropMode + ": Unsupported drop mode for text");
0N/A }
0N/A
0N/A /**
0N/A * Returns the drop mode for this component.
0N/A *
0N/A * @return the drop mode for this component
0N/A * @see #setDropMode
0N/A * @since 1.6
0N/A */
0N/A public final DropMode getDropMode() {
0N/A return dropMode;
0N/A }
0N/A
1338N/A static {
1338N/A SwingAccessor.setJTextComponentAccessor(
1338N/A new SwingAccessor.JTextComponentAccessor() {
1338N/A public TransferHandler.DropLocation dropLocationForPoint(JTextComponent textComp,
1338N/A Point p)
1338N/A {
1338N/A return textComp.dropLocationForPoint(p);
1338N/A }
1338N/A public Object setDropLocation(JTextComponent textComp,
1338N/A TransferHandler.DropLocation location,
1338N/A Object state, boolean forDrop)
1338N/A {
1338N/A return textComp.setDropLocation(location, state, forDrop);
1338N/A }
1338N/A });
1338N/A }
1338N/A
0N/A
0N/A /**
0N/A * Calculates a drop location in this component, representing where a
0N/A * drop at the given point should insert data.
0N/A * <p>
0N/A * Note: This method is meant to override
0N/A * <code>JComponent.dropLocationForPoint()</code>, which is package-private
0N/A * in javax.swing. <code>TransferHandler</code> will detect text components
0N/A * and call this method instead via reflection. It's name should therefore
0N/A * not be changed.
0N/A *
0N/A * @param p the point to calculate a drop location for
0N/A * @return the drop location, or <code>null</code>
0N/A */
0N/A DropLocation dropLocationForPoint(Point p) {
0N/A Position.Bias[] bias = new Position.Bias[1];
0N/A int index = getUI().viewToModel(this, p, bias);
0N/A
0N/A // viewToModel currently returns null for some HTML content
0N/A // when the point is within the component's top inset
0N/A if (bias[0] == null) {
0N/A bias[0] = Position.Bias.Forward;
0N/A }
0N/A
0N/A return new DropLocation(p, index, bias[0]);
0N/A }
0N/A
0N/A /**
0N/A * Called to set or clear the drop location during a DnD operation.
0N/A * In some cases, the component may need to use it's internal selection
0N/A * temporarily to indicate the drop location. To help facilitate this,
0N/A * this method returns and accepts as a parameter a state object.
0N/A * This state object can be used to store, and later restore, the selection
0N/A * state. Whatever this method returns will be passed back to it in
0N/A * future calls, as the state parameter. If it wants the DnD system to
0N/A * continue storing the same state, it must pass it back every time.
0N/A * Here's how this is used:
0N/A * <p>
0N/A * Let's say that on the first call to this method the component decides
0N/A * to save some state (because it is about to use the selection to show
0N/A * a drop index). It can return a state object to the caller encapsulating
0N/A * any saved selection state. On a second call, let's say the drop location
0N/A * is being changed to something else. The component doesn't need to
0N/A * restore anything yet, so it simply passes back the same state object
0N/A * to have the DnD system continue storing it. Finally, let's say this
0N/A * method is messaged with <code>null</code>. This means DnD
0N/A * is finished with this component for now, meaning it should restore
0N/A * state. At this point, it can use the state parameter to restore
0N/A * said state, and of course return <code>null</code> since there's
0N/A * no longer anything to store.
0N/A * <p>
0N/A * Note: This method is meant to override
0N/A * <code>JComponent.setDropLocation()</code>, which is package-private
0N/A * in javax.swing. <code>TransferHandler</code> will detect text components
0N/A * and call this method instead via reflection. It's name should therefore
0N/A * not be changed.
0N/A *
0N/A * @param location the drop location (as calculated by
0N/A * <code>dropLocationForPoint</code>) or <code>null</code>
0N/A * if there's no longer a valid drop location
0N/A * @param state the state object saved earlier for this component,
0N/A * or <code>null</code>
0N/A * @param forDrop whether or not the method is being called because an
0N/A * actual drop occurred
0N/A * @return any saved state for this component, or <code>null</code> if none
0N/A */
0N/A Object setDropLocation(TransferHandler.DropLocation location,
0N/A Object state,
0N/A boolean forDrop) {
0N/A
0N/A Object retVal = null;
0N/A DropLocation textLocation = (DropLocation)location;
0N/A
0N/A if (dropMode == DropMode.USE_SELECTION) {
0N/A if (textLocation == null) {
0N/A if (state != null) {
0N/A /*
0N/A * This object represents the state saved earlier.
0N/A * If the caret is a DefaultCaret it will be
0N/A * an Object array containing, in order:
0N/A * - the saved caret mark (Integer)
0N/A * - the saved caret dot (Integer)
0N/A * - the saved caret visibility (Boolean)
0N/A * - the saved mark bias (Position.Bias)
0N/A * - the saved dot bias (Position.Bias)
0N/A * If the caret is not a DefaultCaret it will
0N/A * be similar, but will not contain the dot
0N/A * or mark bias.
0N/A */
0N/A Object[] vals = (Object[])state;
0N/A
0N/A if (!forDrop) {
0N/A if (caret instanceof DefaultCaret) {
0N/A ((DefaultCaret)caret).setDot(((Integer)vals[0]).intValue(),
0N/A (Position.Bias)vals[3]);
0N/A ((DefaultCaret)caret).moveDot(((Integer)vals[1]).intValue(),
0N/A (Position.Bias)vals[4]);
0N/A } else {
0N/A caret.setDot(((Integer)vals[0]).intValue());
0N/A caret.moveDot(((Integer)vals[1]).intValue());
0N/A }
0N/A }
0N/A
0N/A caret.setVisible(((Boolean)vals[2]).booleanValue());
0N/A }
0N/A } else {
0N/A if (dropLocation == null) {
0N/A boolean visible;
0N/A
0N/A if (caret instanceof DefaultCaret) {
0N/A DefaultCaret dc = (DefaultCaret)caret;
0N/A visible = dc.isActive();
0N/A retVal = new Object[] {Integer.valueOf(dc.getMark()),
0N/A Integer.valueOf(dc.getDot()),
0N/A Boolean.valueOf(visible),
0N/A dc.getMarkBias(),
0N/A dc.getDotBias()};
0N/A } else {
0N/A visible = caret.isVisible();
0N/A retVal = new Object[] {Integer.valueOf(caret.getMark()),
0N/A Integer.valueOf(caret.getDot()),
0N/A Boolean.valueOf(visible)};
0N/A }
0N/A
0N/A caret.setVisible(true);
0N/A } else {
0N/A retVal = state;
0N/A }
0N/A
0N/A if (caret instanceof DefaultCaret) {
0N/A ((DefaultCaret)caret).setDot(textLocation.getIndex(), textLocation.getBias());
0N/A } else {
0N/A caret.setDot(textLocation.getIndex());
0N/A }
0N/A }
0N/A } else {
0N/A if (textLocation == null) {
0N/A if (state != null) {
0N/A caret.setVisible(((Boolean)state).booleanValue());
0N/A }
0N/A } else {
0N/A if (dropLocation == null) {
0N/A boolean visible = caret instanceof DefaultCaret
0N/A ? ((DefaultCaret)caret).isActive()
0N/A : caret.isVisible();
0N/A retVal = Boolean.valueOf(visible);
0N/A caret.setVisible(false);
0N/A } else {
0N/A retVal = state;
0N/A }
0N/A }
0N/A }
0N/A
0N/A DropLocation old = dropLocation;
0N/A dropLocation = textLocation;
0N/A firePropertyChange("dropLocation", old, dropLocation);
0N/A
0N/A return retVal;
0N/A }
0N/A
0N/A /**
0N/A * Returns the location that this component should visually indicate
0N/A * as the drop location during a DnD operation over the component,
0N/A * or {@code null} if no location is to currently be shown.
0N/A * <p>
0N/A * This method is not meant for querying the drop location
0N/A * from a {@code TransferHandler}, as the drop location is only
0N/A * set after the {@code TransferHandler}'s <code>canImport</code>
0N/A * has returned and has allowed for the location to be shown.
0N/A * <p>
0N/A * When this property changes, a property change event with
0N/A * name "dropLocation" is fired by the component.
0N/A *
0N/A * @return the drop location
0N/A * @see #setDropMode
0N/A * @see TransferHandler#canImport(TransferHandler.TransferSupport)
0N/A * @since 1.6
0N/A */
0N/A public final DropLocation getDropLocation() {
0N/A return dropLocation;
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Updates the <code>InputMap</code>s in response to a
0N/A * <code>Keymap</code> change.
0N/A * @param oldKm the old <code>Keymap</code>
0N/A * @param newKm the new <code>Keymap</code>
0N/A */
0N/A void updateInputMap(Keymap oldKm, Keymap newKm) {
0N/A // Locate the current KeymapWrapper.
0N/A InputMap km = getInputMap(JComponent.WHEN_FOCUSED);
0N/A InputMap last = km;
0N/A while (km != null && !(km instanceof KeymapWrapper)) {
0N/A last = km;
0N/A km = km.getParent();
0N/A }
0N/A if (km != null) {
0N/A // Found it, tweak the InputMap that points to it, as well
0N/A // as anything it points to.
0N/A if (newKm == null) {
0N/A if (last != km) {
0N/A last.setParent(km.getParent());
0N/A }
0N/A else {
0N/A last.setParent(null);
0N/A }
0N/A }
0N/A else {
0N/A InputMap newKM = new KeymapWrapper(newKm);
0N/A last.setParent(newKM);
0N/A if (last != km) {
0N/A newKM.setParent(km.getParent());
0N/A }
0N/A }
0N/A }
0N/A else if (newKm != null) {
0N/A km = getInputMap(JComponent.WHEN_FOCUSED);
0N/A if (km != null) {
0N/A // Couldn't find it.
0N/A // Set the parent of WHEN_FOCUSED InputMap to be the new one.
0N/A InputMap newKM = new KeymapWrapper(newKm);
0N/A newKM.setParent(km.getParent());
0N/A km.setParent(newKM);
0N/A }
0N/A }
0N/A
0N/A // Do the same thing with the ActionMap
0N/A ActionMap am = getActionMap();
0N/A ActionMap lastAM = am;
0N/A while (am != null && !(am instanceof KeymapActionMap)) {
0N/A lastAM = am;
0N/A am = am.getParent();
0N/A }
0N/A if (am != null) {
0N/A // Found it, tweak the Actionap that points to it, as well
0N/A // as anything it points to.
0N/A if (newKm == null) {
0N/A if (lastAM != am) {
0N/A lastAM.setParent(am.getParent());
0N/A }
0N/A else {
0N/A lastAM.setParent(null);
0N/A }
0N/A }
0N/A else {
0N/A ActionMap newAM = new KeymapActionMap(newKm);
0N/A lastAM.setParent(newAM);
0N/A if (lastAM != am) {
0N/A newAM.setParent(am.getParent());
0N/A }
0N/A }
0N/A }
0N/A else if (newKm != null) {
0N/A am = getActionMap();
0N/A if (am != null) {
0N/A // Couldn't find it.
0N/A // Set the parent of ActionMap to be the new one.
0N/A ActionMap newAM = new KeymapActionMap(newKm);
0N/A newAM.setParent(am.getParent());
0N/A am.setParent(newAM);
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Fetches the keymap currently active in this text
0N/A * component.
0N/A *
0N/A * @return the keymap
0N/A */
0N/A public Keymap getKeymap() {
0N/A return keymap;
0N/A }
0N/A
0N/A /**
0N/A * Adds a new keymap into the keymap hierarchy. Keymap bindings
0N/A * resolve from bottom up so an attribute specified in a child
0N/A * will override an attribute specified in the parent.
0N/A *
0N/A * @param nm the name of the keymap (must be unique within the
0N/A * collection of named keymaps in the document); the name may
0N/A * be <code>null</code> if the keymap is unnamed,
0N/A * but the caller is responsible for managing the reference
0N/A * returned as an unnamed keymap can't
0N/A * be fetched by name
0N/A * @param parent the parent keymap; this may be <code>null</code> if
0N/A * unspecified bindings need not be resolved in some other keymap
0N/A * @return the keymap
0N/A */
0N/A public static Keymap addKeymap(String nm, Keymap parent) {
0N/A Keymap map = new DefaultKeymap(nm, parent);
0N/A if (nm != null) {
0N/A // add a named keymap, a class of bindings
0N/A getKeymapTable().put(nm, map);
0N/A }
0N/A return map;
0N/A }
0N/A
0N/A /**
0N/A * Removes a named keymap previously added to the document. Keymaps
0N/A * with <code>null</code> names may not be removed in this way.
0N/A *
0N/A * @param nm the name of the keymap to remove
0N/A * @return the keymap that was removed
0N/A */
0N/A public static Keymap removeKeymap(String nm) {
0N/A return getKeymapTable().remove(nm);
0N/A }
0N/A
0N/A /**
0N/A * Fetches a named keymap previously added to the document.
0N/A * This does not work with <code>null</code>-named keymaps.
0N/A *
0N/A * @param nm the name of the keymap
0N/A * @return the keymap
0N/A */
0N/A public static Keymap getKeymap(String nm) {
0N/A return getKeymapTable().get(nm);
0N/A }
0N/A
0N/A private static HashMap<String,Keymap> getKeymapTable() {
0N/A synchronized (KEYMAP_TABLE) {
0N/A AppContext appContext = AppContext.getAppContext();
0N/A HashMap<String,Keymap> keymapTable =
0N/A (HashMap<String,Keymap>)appContext.get(KEYMAP_TABLE);
0N/A if (keymapTable == null) {
0N/A keymapTable = new HashMap<String,Keymap>(17);
0N/A appContext.put(KEYMAP_TABLE, keymapTable);
0N/A //initialize default keymap
0N/A Keymap binding = addKeymap(DEFAULT_KEYMAP, null);
0N/A binding.setDefaultAction(new
0N/A DefaultEditorKit.DefaultKeyTypedAction());
0N/A }
0N/A return keymapTable;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Binding record for creating key bindings.
0N/A * <p>
0N/A * <strong>Warning:</strong>
0N/A * Serialized objects of this class will not be compatible with
0N/A * future Swing releases. The current serialization support is
0N/A * appropriate for short term storage or RMI between applications running
0N/A * the same version of Swing. As of 1.4, support for long term storage
0N/A * of all JavaBeans<sup><font size="-2">TM</font></sup>
0N/A * has been added to the <code>java.beans</code> package.
0N/A * Please see {@link java.beans.XMLEncoder}.
0N/A */
0N/A public static class KeyBinding {
0N/A
0N/A /**
0N/A * The key.
0N/A */
0N/A public KeyStroke key;
0N/A
0N/A /**
0N/A * The name of the action for the key.
0N/A */
0N/A public String actionName;
0N/A
0N/A /**
0N/A * Creates a new key binding.
0N/A *
0N/A * @param key the key
0N/A * @param actionName the name of the action for the key
0N/A */
0N/A public KeyBinding(KeyStroke key, String actionName) {
0N/A this.key = key;
0N/A this.actionName = actionName;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * <p>
0N/A * Loads a keymap with a bunch of
0N/A * bindings. This can be used to take a static table of
0N/A * definitions and load them into some keymap. The following
0N/A * example illustrates an example of binding some keys to
0N/A * the cut, copy, and paste actions associated with a
0N/A * JTextComponent. A code fragment to accomplish
0N/A * this might look as follows:
0N/A * <pre><code>
0N/A *
0N/A * static final JTextComponent.KeyBinding[] defaultBindings = {
0N/A * new JTextComponent.KeyBinding(
0N/A * KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK),
0N/A * DefaultEditorKit.copyAction),
0N/A * new JTextComponent.KeyBinding(
0N/A * KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK),
0N/A * DefaultEditorKit.pasteAction),
0N/A * new JTextComponent.KeyBinding(
0N/A * KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK),
0N/A * DefaultEditorKit.cutAction),
0N/A * };
0N/A *
0N/A * JTextComponent c = new JTextPane();
0N/A * Keymap k = c.getKeymap();
0N/A * JTextComponent.loadKeymap(k, defaultBindings, c.getActions());
0N/A *
0N/A * </code></pre>
0N/A * The sets of bindings and actions may be empty but must be
0N/A * non-<code>null</code>.
0N/A *
0N/A * @param map the keymap
0N/A * @param bindings the bindings
0N/A * @param actions the set of actions
0N/A */
0N/A public static void loadKeymap(Keymap map, KeyBinding[] bindings, Action[] actions) {
611N/A Hashtable<String, Action> h = new Hashtable<String, Action>();
611N/A for (Action a : actions) {
0N/A String value = (String)a.getValue(Action.NAME);
0N/A h.put((value!=null ? value:""), a);
0N/A }
611N/A for (KeyBinding binding : bindings) {
611N/A Action a = h.get(binding.actionName);
0N/A if (a != null) {
611N/A map.addActionForKeyStroke(binding.key, a);
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns true if <code>klass</code> is NOT a JTextComponent and it or
0N/A * one of its superclasses (stoping at JTextComponent) overrides
0N/A * <code>processInputMethodEvent</code>. It is assumed this will be
0N/A * invoked from within a <code>doPrivileged</code>, and it is also
0N/A * assumed <code>klass</code> extends <code>JTextComponent</code>.
0N/A */
611N/A private static Boolean isProcessInputMethodEventOverridden(Class<?> klass) {
0N/A if (klass == JTextComponent.class) {
0N/A return Boolean.FALSE;
0N/A }
611N/A Boolean retValue = overrideMap.get(klass.getName());
0N/A
0N/A if (retValue != null) {
0N/A return retValue;
0N/A }
0N/A Boolean sOverriden = isProcessInputMethodEventOverridden(
0N/A klass.getSuperclass());
0N/A
0N/A if (sOverriden.booleanValue()) {
0N/A // If our superclass has overriden it, then by definition klass
0N/A // overrides it.
0N/A overrideMap.put(klass.getName(), sOverriden);
0N/A return sOverriden;
0N/A }
0N/A // klass's superclass didn't override it, check for an override in
0N/A // klass.
0N/A try {
0N/A Class[] classes = new Class[1];
0N/A classes[0] = InputMethodEvent.class;
0N/A
0N/A Method m = klass.getDeclaredMethod("processInputMethodEvent",
0N/A classes);
0N/A retValue = Boolean.TRUE;
0N/A } catch (NoSuchMethodException nsme) {
0N/A retValue = Boolean.FALSE;
0N/A }
0N/A overrideMap.put(klass.getName(), retValue);
0N/A return retValue;
0N/A }
0N/A
0N/A /**
0N/A * Fetches the current color used to render the
0N/A * caret.
0N/A *
0N/A * @return the color
0N/A */
0N/A public Color getCaretColor() {
0N/A return caretColor;
0N/A }
0N/A
0N/A /**
0N/A * Sets the current color used to render the caret.
0N/A * Setting to <code>null</code> effectively restores the default color.
0N/A * Setting the color results in a PropertyChange event ("caretColor")
0N/A * being fired.
0N/A *
0N/A * @param c the color
0N/A * @see #getCaretColor
0N/A * @beaninfo
0N/A * description: the color used to render the caret
0N/A * bound: true
0N/A * preferred: true
0N/A */
0N/A public void setCaretColor(Color c) {
0N/A Color old = caretColor;
0N/A caretColor = c;
0N/A firePropertyChange("caretColor", old, caretColor);
0N/A }
0N/A
0N/A /**
0N/A * Fetches the current color used to render the
0N/A * selection.
0N/A *
0N/A * @return the color
0N/A */
0N/A public Color getSelectionColor() {
0N/A return selectionColor;
0N/A }
0N/A
0N/A /**
0N/A * Sets the current color used to render the selection.
0N/A * Setting the color to <code>null</code> is the same as setting
0N/A * <code>Color.white</code>. Setting the color results in a
0N/A * PropertyChange event ("selectionColor").
0N/A *
0N/A * @param c the color
0N/A * @see #getSelectionColor
0N/A * @beaninfo
0N/A * description: color used to render selection background
0N/A * bound: true
0N/A * preferred: true
0N/A */
0N/A public void setSelectionColor(Color c) {
0N/A Color old = selectionColor;
0N/A selectionColor = c;
0N/A firePropertyChange("selectionColor", old, selectionColor);
0N/A }
0N/A
0N/A /**
0N/A * Fetches the current color used to render the
0N/A * selected text.
0N/A *
0N/A * @return the color
0N/A */
0N/A public Color getSelectedTextColor() {
0N/A return selectedTextColor;
0N/A }
0N/A
0N/A /**
0N/A * Sets the current color used to render the selected text.
0N/A * Setting the color to <code>null</code> is the same as
0N/A * <code>Color.black</code>. Setting the color results in a
0N/A * PropertyChange event ("selectedTextColor") being fired.
0N/A *
0N/A * @param c the color
0N/A * @see #getSelectedTextColor
0N/A * @beaninfo
0N/A * description: color used to render selected text
0N/A * bound: true
0N/A * preferred: true
0N/A */
0N/A public void setSelectedTextColor(Color c) {
0N/A Color old = selectedTextColor;
0N/A selectedTextColor = c;
0N/A firePropertyChange("selectedTextColor", old, selectedTextColor);
0N/A }
0N/A
0N/A /**
0N/A * Fetches the current color used to render the
0N/A * disabled text.
0N/A *
0N/A * @return the color
0N/A */
0N/A public Color getDisabledTextColor() {
0N/A return disabledTextColor;
0N/A }
0N/A
0N/A /**
0N/A * Sets the current color used to render the
0N/A * disabled text. Setting the color fires off a
0N/A * PropertyChange event ("disabledTextColor").
0N/A *
0N/A * @param c the color
0N/A * @see #getDisabledTextColor
0N/A * @beaninfo
0N/A * description: color used to render disabled text
0N/A * bound: true
0N/A * preferred: true
0N/A */
0N/A public void setDisabledTextColor(Color c) {
0N/A Color old = disabledTextColor;
0N/A disabledTextColor = c;
0N/A firePropertyChange("disabledTextColor", old, disabledTextColor);
0N/A }
0N/A
0N/A /**
0N/A * Replaces the currently selected content with new content
0N/A * represented by the given string. If there is no selection
0N/A * this amounts to an insert of the given text. If there
0N/A * is no replacement text this amounts to a removal of the
0N/A * current selection.
0N/A * <p>
0N/A * This is the method that is used by the default implementation
0N/A * of the action for inserting content that gets bound to the
0N/A * keymap actions.
0N/A *
0N/A * @param content the content to replace the selection with
0N/A */
0N/A public void replaceSelection(String content) {
0N/A Document doc = getDocument();
0N/A if (doc != null) {
0N/A try {
0N/A boolean composedTextSaved = saveComposedText(caret.getDot());
0N/A int p0 = Math.min(caret.getDot(), caret.getMark());
0N/A int p1 = Math.max(caret.getDot(), caret.getMark());
0N/A if (doc instanceof AbstractDocument) {
0N/A ((AbstractDocument)doc).replace(p0, p1 - p0, content,null);
0N/A }
0N/A else {
0N/A if (p0 != p1) {
0N/A doc.remove(p0, p1 - p0);
0N/A }
0N/A if (content != null && content.length() > 0) {
0N/A doc.insertString(p0, content, null);
0N/A }
0N/A }
0N/A if (composedTextSaved) {
0N/A restoreComposedText();
0N/A }
0N/A } catch (BadLocationException e) {
0N/A UIManager.getLookAndFeel().provideErrorFeedback(JTextComponent.this);
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Fetches a portion of the text represented by the
0N/A * component. Returns an empty string if length is 0.
0N/A *
0N/A * @param offs the offset >= 0
0N/A * @param len the length >= 0
0N/A * @return the text
0N/A * @exception BadLocationException if the offset or length are invalid
0N/A */
0N/A public String getText(int offs, int len) throws BadLocationException {
0N/A return getDocument().getText(offs, len);
0N/A }
0N/A
0N/A /**
0N/A * Converts the given location in the model to a place in
0N/A * the view coordinate system.
0N/A * The component must have a positive size for
0N/A * this translation to be computed (i.e. layout cannot
0N/A * be computed until the component has been sized). The
0N/A * component does not have to be visible or painted.
0N/A *
0N/A * @param pos the position >= 0
0N/A * @return the coordinates as a rectangle, with (r.x, r.y) as the location
0N/A * in the coordinate system, or null if the component does
0N/A * not yet have a positive size.
0N/A * @exception BadLocationException if the given position does not
0N/A * represent a valid location in the associated document
0N/A * @see TextUI#modelToView
0N/A */
0N/A public Rectangle modelToView(int pos) throws BadLocationException {
0N/A return getUI().modelToView(this, pos);
0N/A }
0N/A
0N/A /**
0N/A * Converts the given place in the view coordinate system
0N/A * to the nearest representative location in the model.
0N/A * The component must have a positive size for
0N/A * this translation to be computed (i.e. layout cannot
0N/A * be computed until the component has been sized). The
0N/A * component does not have to be visible or painted.
0N/A *
0N/A * @param pt the location in the view to translate
0N/A * @return the offset >= 0 from the start of the document,
0N/A * or -1 if the component does not yet have a positive
0N/A * size.
0N/A * @see TextUI#viewToModel
0N/A */
0N/A public int viewToModel(Point pt) {
0N/A return getUI().viewToModel(this, pt);
0N/A }
0N/A
0N/A /**
0N/A * Transfers the currently selected range in the associated
0N/A * text model to the system clipboard, removing the contents
0N/A * from the model. The current selection is reset. Does nothing
0N/A * for <code>null</code> selections.
0N/A *
0N/A * @see java.awt.Toolkit#getSystemClipboard
0N/A * @see java.awt.datatransfer.Clipboard
0N/A */
0N/A public void cut() {
0N/A if (isEditable() && isEnabled()) {
0N/A invokeAction("cut", TransferHandler.getCutAction());
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Transfers the currently selected range in the associated
0N/A * text model to the system clipboard, leaving the contents
0N/A * in the text model. The current selection remains intact.
0N/A * Does nothing for <code>null</code> selections.
0N/A *
0N/A * @see java.awt.Toolkit#getSystemClipboard
0N/A * @see java.awt.datatransfer.Clipboard
0N/A */
0N/A public void copy() {
0N/A invokeAction("copy", TransferHandler.getCopyAction());
0N/A }
0N/A
0N/A /**
0N/A * Transfers the contents of the system clipboard into the
0N/A * associated text model. If there is a selection in the
0N/A * associated view, it is replaced with the contents of the
0N/A * clipboard. If there is no selection, the clipboard contents
0N/A * are inserted in front of the current insert position in
0N/A * the associated view. If the clipboard is empty, does nothing.
0N/A *
0N/A * @see #replaceSelection
0N/A * @see java.awt.Toolkit#getSystemClipboard
0N/A * @see java.awt.datatransfer.Clipboard
0N/A */
0N/A public void paste() {
0N/A if (isEditable() && isEnabled()) {
0N/A invokeAction("paste", TransferHandler.getPasteAction());
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * This is a conveniance method that is only useful for
0N/A * <code>cut</code>, <code>copy</code> and <code>paste</code>. If
0N/A * an <code>Action</code> with the name <code>name</code> does not
0N/A * exist in the <code>ActionMap</code>, this will attemp to install a
0N/A * <code>TransferHandler</code> and then use <code>altAction</code>.
0N/A */
0N/A private void invokeAction(String name, Action altAction) {
0N/A ActionMap map = getActionMap();
0N/A Action action = null;
0N/A
0N/A if (map != null) {
0N/A action = map.get(name);
0N/A }
0N/A if (action == null) {
0N/A installDefaultTransferHandlerIfNecessary();
0N/A action = altAction;
0N/A }
0N/A action.actionPerformed(new ActionEvent(this,
0N/A ActionEvent.ACTION_PERFORMED, (String)action.
0N/A getValue(Action.NAME),
0N/A EventQueue.getMostRecentEventTime(),
0N/A getCurrentEventModifiers()));
0N/A }
0N/A
0N/A /**
0N/A * If the current <code>TransferHandler</code> is null, this will
0N/A * install a new one.
0N/A */
0N/A private void installDefaultTransferHandlerIfNecessary() {
0N/A if (getTransferHandler() == null) {
0N/A if (defaultTransferHandler == null) {
0N/A defaultTransferHandler = new DefaultTransferHandler();
0N/A }
0N/A setTransferHandler(defaultTransferHandler);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Moves the caret to a new position, leaving behind a mark
0N/A * defined by the last time <code>setCaretPosition</code> was
0N/A * called. This forms a selection.
0N/A * If the document is <code>null</code>, does nothing. The position
0N/A * must be between 0 and the length of the component's text or else
0N/A * an exception is thrown.
0N/A *
0N/A * @param pos the position
0N/A * @exception IllegalArgumentException if the value supplied
0N/A * for <code>position</code> is less than zero or greater
0N/A * than the component's text length
0N/A * @see #setCaretPosition
0N/A */
0N/A public void moveCaretPosition(int pos) {
0N/A Document doc = getDocument();
0N/A if (doc != null) {
0N/A if (pos > doc.getLength() || pos < 0) {
0N/A throw new IllegalArgumentException("bad position: " + pos);
0N/A }
0N/A caret.moveDot(pos);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * The bound property name for the focus accelerator.
0N/A */
0N/A public static final String FOCUS_ACCELERATOR_KEY = "focusAcceleratorKey";
0N/A
0N/A /**
0N/A * Sets the key accelerator that will cause the receiving text
0N/A * component to get the focus. The accelerator will be the
0N/A * key combination of the <em>alt</em> key and the character
0N/A * given (converted to upper case). By default, there is no focus
0N/A * accelerator key. Any previous key accelerator setting will be
0N/A * superseded. A '\0' key setting will be registered, and has the
0N/A * effect of turning off the focus accelerator. When the new key
0N/A * is set, a PropertyChange event (FOCUS_ACCELERATOR_KEY) will be fired.
0N/A *
0N/A * @param aKey the key
0N/A * @see #getFocusAccelerator
0N/A * @beaninfo
0N/A * description: accelerator character used to grab focus
0N/A * bound: true
0N/A */
0N/A public void setFocusAccelerator(char aKey) {
0N/A aKey = Character.toUpperCase(aKey);
0N/A char old = focusAccelerator;
0N/A focusAccelerator = aKey;
0N/A // Fix for 4341002: value of FOCUS_ACCELERATOR_KEY is wrong.
0N/A // So we fire both FOCUS_ACCELERATOR_KEY, for compatibility,
0N/A // and the correct event here.
0N/A firePropertyChange(FOCUS_ACCELERATOR_KEY, old, focusAccelerator);
0N/A firePropertyChange("focusAccelerator", old, focusAccelerator);
0N/A }
0N/A
0N/A /**
0N/A * Returns the key accelerator that will cause the receiving
0N/A * text component to get the focus. Return '\0' if no focus
0N/A * accelerator has been set.
0N/A *
0N/A * @return the key
0N/A */
0N/A public char getFocusAccelerator() {
0N/A return focusAccelerator;
0N/A }
0N/A
0N/A /**
0N/A * Initializes from a stream. This creates a
0N/A * model of the type appropriate for the component
0N/A * and initializes the model from the stream.
0N/A * By default this will load the model as plain
0N/A * text. Previous contents of the model are discarded.
0N/A *
0N/A * @param in the stream to read from
0N/A * @param desc an object describing the stream; this
0N/A * might be a string, a File, a URL, etc. Some kinds
0N/A * of documents (such as html for example) might be
0N/A * able to make use of this information; if non-<code>null</code>,
0N/A * it is added as a property of the document
0N/A * @exception IOException as thrown by the stream being
0N/A * used to initialize
0N/A * @see EditorKit#createDefaultDocument
0N/A * @see #setDocument
0N/A * @see PlainDocument
0N/A */
0N/A public void read(Reader in, Object desc) throws IOException {
0N/A EditorKit kit = getUI().getEditorKit(this);
0N/A Document doc = kit.createDefaultDocument();
0N/A if (desc != null) {
0N/A doc.putProperty(Document.StreamDescriptionProperty, desc);
0N/A }
0N/A try {
0N/A kit.read(in, doc, 0);
0N/A setDocument(doc);
0N/A } catch (BadLocationException e) {
0N/A throw new IOException(e.getMessage());
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Stores the contents of the model into the given
0N/A * stream. By default this will store the model as plain
0N/A * text.
0N/A *
0N/A * @param out the output stream
0N/A * @exception IOException on any I/O error
0N/A */
0N/A public void write(Writer out) throws IOException {
0N/A Document doc = getDocument();
0N/A try {
0N/A getUI().getEditorKit(this).write(out, doc, 0, doc.getLength());
0N/A } catch (BadLocationException e) {
0N/A throw new IOException(e.getMessage());
0N/A }
0N/A }
0N/A
0N/A public void removeNotify() {
0N/A super.removeNotify();
0N/A if (getFocusedComponent() == this) {
0N/A AppContext.getAppContext().remove(FOCUSED_COMPONENT);
0N/A }
0N/A }
0N/A
0N/A // --- java.awt.TextComponent methods ------------------------
0N/A
0N/A /**
0N/A * Sets the position of the text insertion caret for the
0N/A * <code>TextComponent</code>. Note that the caret tracks change,
0N/A * so this may move if the underlying text of the component is changed.
0N/A * If the document is <code>null</code>, does nothing. The position
0N/A * must be between 0 and the length of the component's text or else
0N/A * an exception is thrown.
0N/A *
0N/A * @param position the position
0N/A * @exception IllegalArgumentException if the value supplied
0N/A * for <code>position</code> is less than zero or greater
0N/A * than the component's text length
0N/A * @beaninfo
0N/A * description: the caret position
0N/A */
0N/A public void setCaretPosition(int position) {
0N/A Document doc = getDocument();
0N/A if (doc != null) {
0N/A if (position > doc.getLength() || position < 0) {
0N/A throw new IllegalArgumentException("bad position: " + position);
0N/A }
0N/A caret.setDot(position);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns the position of the text insertion caret for the
0N/A * text component.
0N/A *
0N/A * @return the position of the text insertion caret for the
0N/A * text component >= 0
0N/A */
243N/A @Transient
0N/A public int getCaretPosition() {
0N/A return caret.getDot();
0N/A }
0N/A
0N/A /**
0N/A * Sets the text of this <code>TextComponent</code>
0N/A * to the specified text. If the text is <code>null</code>
0N/A * or empty, has the effect of simply deleting the old text.
0N/A * When text has been inserted, the resulting caret location
0N/A * is determined by the implementation of the caret class.
187N/A *
0N/A * <p>
0N/A * Note that text is not a bound property, so no <code>PropertyChangeEvent
0N/A * </code> is fired when it changes. To listen for changes to the text,
0N/A * use <code>DocumentListener</code>.
0N/A *
0N/A * @param t the new text to be set
0N/A * @see #getText
0N/A * @see DefaultCaret
0N/A * @beaninfo
0N/A * description: the text of this component
0N/A */
0N/A public void setText(String t) {
0N/A try {
0N/A Document doc = getDocument();
0N/A if (doc instanceof AbstractDocument) {
0N/A ((AbstractDocument)doc).replace(0, doc.getLength(), t,null);
0N/A }
0N/A else {
0N/A doc.remove(0, doc.getLength());
0N/A doc.insertString(0, t, null);
0N/A }
0N/A } catch (BadLocationException e) {
0N/A UIManager.getLookAndFeel().provideErrorFeedback(JTextComponent.this);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns the text contained in this <code>TextComponent</code>.
0N/A * If the underlying document is <code>null</code>,
0N/A * will give a <code>NullPointerException</code>.
0N/A *
0N/A * Note that text is not a bound property, so no <code>PropertyChangeEvent
0N/A * </code> is fired when it changes. To listen for changes to the text,
0N/A * use <code>DocumentListener</code>.
0N/A *
0N/A * @return the text
0N/A * @exception NullPointerException if the document is <code>null</code>
0N/A * @see #setText
0N/A */
0N/A public String getText() {
0N/A Document doc = getDocument();
0N/A String txt;
0N/A try {
0N/A txt = doc.getText(0, doc.getLength());
0N/A } catch (BadLocationException e) {
0N/A txt = null;
0N/A }
0N/A return txt;
0N/A }
0N/A
0N/A /**
0N/A * Returns the selected text contained in this
0N/A * <code>TextComponent</code>. If the selection is
0N/A * <code>null</code> or the document empty, returns <code>null</code>.
0N/A *
0N/A * @return the text
0N/A * @exception IllegalArgumentException if the selection doesn't
0N/A * have a valid mapping into the document for some reason
0N/A * @see #setText
0N/A */
0N/A public String getSelectedText() {
0N/A String txt = null;
0N/A int p0 = Math.min(caret.getDot(), caret.getMark());
0N/A int p1 = Math.max(caret.getDot(), caret.getMark());
0N/A if (p0 != p1) {
0N/A try {
0N/A Document doc = getDocument();
0N/A txt = doc.getText(p0, p1 - p0);
0N/A } catch (BadLocationException e) {
0N/A throw new IllegalArgumentException(e.getMessage());
0N/A }
0N/A }
0N/A return txt;
0N/A }
0N/A
0N/A /**
0N/A * Returns the boolean indicating whether this
0N/A * <code>TextComponent</code> is editable or not.
0N/A *
0N/A * @return the boolean value
0N/A * @see #setEditable
0N/A */
0N/A public boolean isEditable() {
0N/A return editable;
0N/A }
0N/A
0N/A /**
0N/A * Sets the specified boolean to indicate whether or not this
0N/A * <code>TextComponent</code> should be editable.
0N/A * A PropertyChange event ("editable") is fired when the
0N/A * state is changed.
0N/A *
0N/A * @param b the boolean to be set
0N/A * @see #isEditable
0N/A * @beaninfo
0N/A * description: specifies if the text can be edited
0N/A * bound: true
0N/A */
0N/A public void setEditable(boolean b) {
0N/A if (b != editable) {
0N/A boolean oldVal = editable;
0N/A editable = b;
0N/A enableInputMethods(editable);
0N/A firePropertyChange("editable", Boolean.valueOf(oldVal), Boolean.valueOf(editable));
0N/A repaint();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns the selected text's start position. Return 0 for an
0N/A * empty document, or the value of dot if no selection.
0N/A *
0N/A * @return the start position >= 0
0N/A */
243N/A @Transient
0N/A public int getSelectionStart() {
0N/A int start = Math.min(caret.getDot(), caret.getMark());
0N/A return start;
0N/A }
0N/A
0N/A /**
0N/A * Sets the selection start to the specified position. The new
0N/A * starting point is constrained to be before or at the current
0N/A * selection end.
0N/A * <p>
0N/A * This is available for backward compatibility to code
0N/A * that called this method on <code>java.awt.TextComponent</code>.
0N/A * This is implemented to forward to the <code>Caret</code>
0N/A * implementation which is where the actual selection is maintained.
0N/A *
0N/A * @param selectionStart the start position of the text >= 0
0N/A * @beaninfo
0N/A * description: starting location of the selection.
0N/A */
0N/A public void setSelectionStart(int selectionStart) {
0N/A /* Route through select method to enforce consistent policy
0N/A * between selectionStart and selectionEnd.
0N/A */
0N/A select(selectionStart, getSelectionEnd());
0N/A }
0N/A
0N/A /**
0N/A * Returns the selected text's end position. Return 0 if the document
0N/A * is empty, or the value of dot if there is no selection.
0N/A *
0N/A * @return the end position >= 0
0N/A */
243N/A @Transient
0N/A public int getSelectionEnd() {
0N/A int end = Math.max(caret.getDot(), caret.getMark());
0N/A return end;
0N/A }
0N/A
0N/A /**
0N/A * Sets the selection end to the specified position. The new
0N/A * end point is constrained to be at or after the current
0N/A * selection start.
0N/A * <p>
0N/A * This is available for backward compatibility to code
0N/A * that called this method on <code>java.awt.TextComponent</code>.
0N/A * This is implemented to forward to the <code>Caret</code>
0N/A * implementation which is where the actual selection is maintained.
0N/A *
0N/A * @param selectionEnd the end position of the text >= 0
0N/A * @beaninfo
0N/A * description: ending location of the selection.
0N/A */
0N/A public void setSelectionEnd(int selectionEnd) {
0N/A /* Route through select method to enforce consistent policy
0N/A * between selectionStart and selectionEnd.
0N/A */
0N/A select(getSelectionStart(), selectionEnd);
0N/A }
0N/A
0N/A /**
0N/A * Selects the text between the specified start and end positions.
0N/A * <p>
0N/A * This method sets the start and end positions of the
0N/A * selected text, enforcing the restriction that the start position
0N/A * must be greater than or equal to zero. The end position must be
0N/A * greater than or equal to the start position, and less than or
0N/A * equal to the length of the text component's text.
0N/A * <p>
0N/A * If the caller supplies values that are inconsistent or out of
0N/A * bounds, the method enforces these constraints silently, and
0N/A * without failure. Specifically, if the start position or end
0N/A * position is greater than the length of the text, it is reset to
0N/A * equal the text length. If the start position is less than zero,
0N/A * it is reset to zero, and if the end position is less than the
0N/A * start position, it is reset to the start position.
0N/A * <p>
0N/A * This call is provided for backward compatibility.
0N/A * It is routed to a call to <code>setCaretPosition</code>
0N/A * followed by a call to <code>moveCaretPosition</code>.
0N/A * The preferred way to manage selection is by calling
0N/A * those methods directly.
0N/A *
0N/A * @param selectionStart the start position of the text
0N/A * @param selectionEnd the end position of the text
0N/A * @see #setCaretPosition
0N/A * @see #moveCaretPosition
0N/A */
0N/A public void select(int selectionStart, int selectionEnd) {
0N/A // argument adjustment done by java.awt.TextComponent
0N/A int docLength = getDocument().getLength();
0N/A
0N/A if (selectionStart < 0) {
0N/A selectionStart = 0;
0N/A }
0N/A if (selectionStart > docLength) {
0N/A selectionStart = docLength;
0N/A }
0N/A if (selectionEnd > docLength) {
0N/A selectionEnd = docLength;
0N/A }
0N/A if (selectionEnd < selectionStart) {
0N/A selectionEnd = selectionStart;
0N/A }
0N/A
0N/A setCaretPosition(selectionStart);
0N/A moveCaretPosition(selectionEnd);
0N/A }
0N/A
0N/A /**
0N/A * Selects all the text in the <code>TextComponent</code>.
0N/A * Does nothing on a <code>null</code> or empty document.
0N/A */
0N/A public void selectAll() {
0N/A Document doc = getDocument();
0N/A if (doc != null) {
0N/A setCaretPosition(0);
0N/A moveCaretPosition(doc.getLength());
0N/A }
0N/A }
0N/A
0N/A // --- Tooltip Methods ---------------------------------------------
0N/A
0N/A /**
0N/A * Returns the string to be used as the tooltip for <code>event</code>.
0N/A * This will return one of:
0N/A * <ol>
0N/A * <li>If <code>setToolTipText</code> has been invoked with a
0N/A * non-<code>null</code>
0N/A * value, it will be returned, otherwise
0N/A * <li>The value from invoking <code>getToolTipText</code> on
0N/A * the UI will be returned.
0N/A * </ol>
0N/A * By default <code>JTextComponent</code> does not register
0N/A * itself with the <code>ToolTipManager</code>.
0N/A * This means that tooltips will NOT be shown from the
0N/A * <code>TextUI</code> unless <code>registerComponent</code> has
0N/A * been invoked on the <code>ToolTipManager</code>.
0N/A *
0N/A * @param event the event in question
0N/A * @return the string to be used as the tooltip for <code>event</code>
0N/A * @see javax.swing.JComponent#setToolTipText
0N/A * @see javax.swing.plaf.TextUI#getToolTipText
0N/A * @see javax.swing.ToolTipManager#registerComponent
0N/A */
0N/A public String getToolTipText(MouseEvent event) {
0N/A String retValue = super.getToolTipText(event);
0N/A
0N/A if (retValue == null) {
0N/A TextUI ui = getUI();
0N/A if (ui != null) {
0N/A retValue = ui.getToolTipText(this, new Point(event.getX(),
0N/A event.getY()));
0N/A }
0N/A }
0N/A return retValue;
0N/A }
0N/A
0N/A // --- Scrollable methods ---------------------------------------------
0N/A
0N/A /**
0N/A * Returns the preferred size of the viewport for a view component.
0N/A * This is implemented to do the default behavior of returning
0N/A * the preferred size of the component.
0N/A *
0N/A * @return the <code>preferredSize</code> of a <code>JViewport</code>
0N/A * whose view is this <code>Scrollable</code>
0N/A */
0N/A public Dimension getPreferredScrollableViewportSize() {
0N/A return getPreferredSize();
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Components that display logical rows or columns should compute
0N/A * the scroll increment that will completely expose one new row
0N/A * or column, depending on the value of orientation. Ideally,
0N/A * components should handle a partially exposed row or column by
0N/A * returning the distance required to completely expose the item.
0N/A * <p>
0N/A * The default implementation of this is to simply return 10% of
0N/A * the visible area. Subclasses are likely to be able to provide
0N/A * a much more reasonable value.
0N/A *
0N/A * @param visibleRect the view area visible within the viewport
0N/A * @param orientation either <code>SwingConstants.VERTICAL</code> or
0N/A * <code>SwingConstants.HORIZONTAL</code>
0N/A * @param direction less than zero to scroll up/left, greater than
0N/A * zero for down/right
0N/A * @return the "unit" increment for scrolling in the specified direction
0N/A * @exception IllegalArgumentException for an invalid orientation
0N/A * @see JScrollBar#setUnitIncrement
0N/A */
0N/A public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
0N/A switch(orientation) {
0N/A case SwingConstants.VERTICAL:
0N/A return visibleRect.height / 10;
0N/A case SwingConstants.HORIZONTAL:
0N/A return visibleRect.width / 10;
0N/A default:
0N/A throw new IllegalArgumentException("Invalid orientation: " + orientation);
0N/A }
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Components that display logical rows or columns should compute
0N/A * the scroll increment that will completely expose one block
0N/A * of rows or columns, depending on the value of orientation.
0N/A * <p>
0N/A * The default implementation of this is to simply return the visible
0N/A * area. Subclasses will likely be able to provide a much more
0N/A * reasonable value.
0N/A *
0N/A * @param visibleRect the view area visible within the viewport
0N/A * @param orientation either <code>SwingConstants.VERTICAL</code> or
0N/A * <code>SwingConstants.HORIZONTAL</code>
0N/A * @param direction less than zero to scroll up/left, greater than zero
0N/A * for down/right
0N/A * @return the "block" increment for scrolling in the specified direction
0N/A * @exception IllegalArgumentException for an invalid orientation
0N/A * @see JScrollBar#setBlockIncrement
0N/A */
0N/A public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
0N/A switch(orientation) {
0N/A case SwingConstants.VERTICAL:
0N/A return visibleRect.height;
0N/A case SwingConstants.HORIZONTAL:
0N/A return visibleRect.width;
0N/A default:
0N/A throw new IllegalArgumentException("Invalid orientation: " + orientation);
0N/A }
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Returns true if a viewport should always force the width of this
0N/A * <code>Scrollable</code> to match the width of the viewport.
0N/A * For example a normal text view that supported line wrapping
0N/A * would return true here, since it would be undesirable for
0N/A * wrapped lines to disappear beyond the right
0N/A * edge of the viewport. Note that returning true for a
0N/A * <code>Scrollable</code> whose ancestor is a <code>JScrollPane</code>
0N/A * effectively disables horizontal scrolling.
0N/A * <p>
0N/A * Scrolling containers, like <code>JViewport</code>,
0N/A * will use this method each time they are validated.
0N/A *
0N/A * @return true if a viewport should force the <code>Scrollable</code>s
0N/A * width to match its own
0N/A */
0N/A public boolean getScrollableTracksViewportWidth() {
2333N/A Container parent = SwingUtilities.getUnwrappedParent(this);
2333N/A if (parent instanceof JViewport) {
2333N/A return parent.getWidth() > getPreferredSize().width;
0N/A }
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Returns true if a viewport should always force the height of this
0N/A * <code>Scrollable</code> to match the height of the viewport.
0N/A * For example a columnar text view that flowed text in left to
0N/A * right columns could effectively disable vertical scrolling by
0N/A * returning true here.
0N/A * <p>
0N/A * Scrolling containers, like <code>JViewport</code>,
0N/A * will use this method each time they are validated.
0N/A *
0N/A * @return true if a viewport should force the Scrollables height
0N/A * to match its own
0N/A */
0N/A public boolean getScrollableTracksViewportHeight() {
2333N/A Container parent = SwingUtilities.getUnwrappedParent(this);
2333N/A if (parent instanceof JViewport) {
2333N/A return parent.getHeight() > getPreferredSize().height;
0N/A }
0N/A return false;
0N/A }
0N/A
0N/A
0N/A//////////////////
0N/A// Printing Support
0N/A//////////////////
0N/A
0N/A /**
0N/A * A convenience print method that displays a print dialog, and then
0N/A * prints this {@code JTextComponent} in <i>interactive</i> mode with no
0N/A * header or footer text. Note: this method
0N/A * blocks until printing is done.
0N/A * <p>
0N/A * Note: In <i>headless</i> mode, no dialogs will be shown.
0N/A *
0N/A * <p> This method calls the full featured
0N/A * {@link #print(MessageFormat, MessageFormat, boolean, PrintService, PrintRequestAttributeSet, boolean)
0N/A * print} method to perform printing.
0N/A * @return {@code true}, unless printing is canceled by the user
0N/A * @throws PrinterException if an error in the print system causes the job
0N/A * to be aborted
0N/A * @throws SecurityException if this thread is not allowed to
0N/A * initiate a print job request
0N/A *
0N/A * @see #print(MessageFormat, MessageFormat, boolean, PrintService, PrintRequestAttributeSet, boolean)
0N/A *
0N/A * @since 1.6
0N/A */
0N/A
0N/A public boolean print() throws PrinterException {
0N/A return print(null, null, true, null, null, true);
0N/A }
0N/A
0N/A /**
0N/A * A convenience print method that displays a print dialog, and then
0N/A * prints this {@code JTextComponent} in <i>interactive</i> mode with
0N/A * the specified header and footer text. Note: this method
0N/A * blocks until printing is done.
0N/A * <p>
0N/A * Note: In <i>headless</i> mode, no dialogs will be shown.
0N/A *
0N/A * <p> This method calls the full featured
0N/A * {@link #print(MessageFormat, MessageFormat, boolean, PrintService, PrintRequestAttributeSet, boolean)
0N/A * print} method to perform printing.
0N/A * @param headerFormat the text, in {@code MessageFormat}, to be
0N/A * used as the header, or {@code null} for no header
0N/A * @param footerFormat the text, in {@code MessageFormat}, to be
0N/A * used as the footer, or {@code null} for no footer
0N/A * @return {@code true}, unless printing is canceled by the user
0N/A * @throws PrinterException if an error in the print system causes the job
0N/A * to be aborted
0N/A * @throws SecurityException if this thread is not allowed to
0N/A * initiate a print job request
0N/A *
0N/A * @see #print(MessageFormat, MessageFormat, boolean, PrintService, PrintRequestAttributeSet, boolean)
0N/A * @see java.text.MessageFormat
0N/A * @since 1.6
0N/A */
0N/A public boolean print(final MessageFormat headerFormat,
0N/A final MessageFormat footerFormat) throws PrinterException {
0N/A return print(headerFormat, footerFormat, true, null, null, true);
0N/A }
0N/A
0N/A /**
0N/A * Prints the content of this {@code JTextComponent}. Note: this method
0N/A * blocks until printing is done.
0N/A *
0N/A * <p>
0N/A * Page header and footer text can be added to the output by providing
0N/A * {@code MessageFormat} arguments. The printing code requests
0N/A * {@code Strings} from the formats, providing a single item which may be
0N/A * included in the formatted string: an {@code Integer} representing the
0N/A * current page number.
0N/A *
0N/A * <p>
0N/A * {@code showPrintDialog boolean} parameter allows you to specify whether
0N/A * a print dialog is displayed to the user. When it is, the user
0N/A * may use the dialog to change printing attributes or even cancel the
0N/A * print.
0N/A *
0N/A * <p>
0N/A * {@code service} allows you to provide the initial
0N/A * {@code PrintService} for the print dialog, or to specify
0N/A * {@code PrintService} to print to when the dialog is not shown.
0N/A *
0N/A * <p>
0N/A * {@code attributes} can be used to provide the
0N/A * initial values for the print dialog, or to supply any needed
0N/A * attributes when the dialog is not shown. {@code attributes} can
0N/A * be used to control how the job will print, for example
0N/A * <i>duplex</i> or <i>single-sided</i>.
0N/A *
0N/A * <p>
0N/A * {@code interactive boolean} parameter allows you to specify
0N/A * whether to perform printing in <i>interactive</i>
0N/A * mode. If {@code true}, a progress dialog, with an abort option,
0N/A * is displayed for the duration of printing. This dialog is
0N/A * <i>modal</i> when {@code print} is invoked on the <i>Event Dispatch
0N/A * Thread</i> and <i>non-modal</i> otherwise. <b>Warning</b>:
0N/A * calling this method on the <i>Event Dispatch Thread</i> with {@code
0N/A * interactive false} blocks <i>all</i> events, including repaints, from
0N/A * being processed until printing is complete. It is only
0N/A * recommended when printing from an application with no
0N/A * visible GUI.
0N/A *
0N/A * <p>
0N/A * Note: In <i>headless</i> mode, {@code showPrintDialog} and
0N/A * {@code interactive} parameters are ignored and no dialogs are
0N/A * shown.
0N/A *
0N/A * <p>
0N/A * This method ensures the {@code document} is not mutated during printing.
0N/A * To indicate it visually, {@code setEnabled(false)} is set for the
0N/A * duration of printing.
0N/A *
0N/A * <p>
0N/A * This method uses {@link #getPrintable} to render document content.
0N/A *
0N/A * <p>
0N/A * This method is thread-safe, although most Swing methods are not. Please
0N/A * see <A
0N/A * HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">
0N/A * How to Use Threads</A> for more information.
0N/A *
0N/A * <p>
0N/A * <b>Sample Usage</b>. This code snippet shows a cross-platform print
0N/A * dialog and then prints the {@code JTextComponent} in <i>interactive</i> mode
0N/A * unless the user cancels the dialog:
0N/A *
0N/A * <pre>
0N/A * textComponent.print(new MessageFormat(&quot;My text component header&quot;),
0N/A * new MessageFormat(&quot;Footer. Page - {0}&quot;), true, null, null, true);
0N/A * </pre>
0N/A * <p>
0N/A * Executing this code off the <i>Event Dispatch Thread</i>
0N/A * performs printing on the <i>background</i>.
0N/A * The following pattern might be used for <i>background</i>
0N/A * printing:
0N/A * <pre>
0N/A * FutureTask&lt;Boolean&gt; future =
0N/A * new FutureTask&lt;Boolean&gt;(
0N/A * new Callable&lt;Boolean&gt;() {
0N/A * public Boolean call() {
0N/A * return textComponent.print(.....);
0N/A * }
0N/A * });
0N/A * executor.execute(future);
0N/A * </pre>
0N/A *
0N/A * @param headerFormat the text, in {@code MessageFormat}, to be
0N/A * used as the header, or {@code null} for no header
0N/A * @param footerFormat the text, in {@code MessageFormat}, to be
0N/A * used as the footer, or {@code null} for no footer
0N/A * @param showPrintDialog {@code true} to display a print dialog,
0N/A * {@code false} otherwise
0N/A * @param service initial {@code PrintService}, or {@code null} for the
0N/A * default
0N/A * @param attributes the job attributes to be applied to the print job, or
0N/A * {@code null} for none
0N/A * @param interactive whether to print in an interactive mode
0N/A * @return {@code true}, unless printing is canceled by the user
0N/A * @throws PrinterException if an error in the print system causes the job
0N/A * to be aborted
0N/A * @throws SecurityException if this thread is not allowed to
0N/A * initiate a print job request
0N/A *
0N/A * @see #getPrintable
0N/A * @see java.text.MessageFormat
0N/A * @see java.awt.GraphicsEnvironment#isHeadless
0N/A * @see java.util.concurrent.FutureTask
0N/A *
0N/A * @since 1.6
0N/A */
0N/A public boolean print(final MessageFormat headerFormat,
0N/A final MessageFormat footerFormat,
0N/A final boolean showPrintDialog,
0N/A final PrintService service,
0N/A final PrintRequestAttributeSet attributes,
0N/A final boolean interactive)
0N/A throws PrinterException {
0N/A
0N/A final PrinterJob job = PrinterJob.getPrinterJob();
0N/A final Printable printable;
0N/A final PrintingStatus printingStatus;
0N/A final boolean isHeadless = GraphicsEnvironment.isHeadless();
0N/A final boolean isEventDispatchThread =
0N/A SwingUtilities.isEventDispatchThread();
0N/A final Printable textPrintable = getPrintable(headerFormat, footerFormat);
0N/A if (interactive && ! isHeadless) {
0N/A printingStatus =
0N/A PrintingStatus.createPrintingStatus(this, job);
0N/A printable =
0N/A printingStatus.createNotificationPrintable(textPrintable);
0N/A } else {
0N/A printingStatus = null;
0N/A printable = textPrintable;
0N/A }
0N/A
0N/A if (service != null) {
0N/A job.setPrintService(service);
0N/A }
0N/A
0N/A job.setPrintable(printable);
0N/A
0N/A final PrintRequestAttributeSet attr = (attributes == null)
0N/A ? new HashPrintRequestAttributeSet()
0N/A : attributes;
0N/A
0N/A if (showPrintDialog && ! isHeadless && ! job.printDialog(attr)) {
0N/A return false;
0N/A }
0N/A
0N/A /*
0N/A * there are three cases for printing:
0N/A * 1. print non interactively (! interactive || isHeadless)
0N/A * 2. print interactively off EDT
0N/A * 3. print interactively on EDT
0N/A *
0N/A * 1 and 2 prints on the current thread (3 prints on another thread)
0N/A * 2 and 3 deal with PrintingStatusDialog
0N/A */
0N/A final Callable<Object> doPrint =
0N/A new Callable<Object>() {
0N/A public Object call() throws Exception {
0N/A try {
0N/A job.print(attr);
0N/A } finally {
0N/A if (printingStatus != null) {
0N/A printingStatus.dispose();
0N/A }
0N/A }
0N/A return null;
0N/A }
0N/A };
0N/A
0N/A final FutureTask<Object> futurePrinting =
0N/A new FutureTask<Object>(doPrint);
0N/A
0N/A final Runnable runnablePrinting =
0N/A new Runnable() {
0N/A public void run() {
0N/A //disable component
0N/A boolean wasEnabled = false;
0N/A if (isEventDispatchThread) {
0N/A if (isEnabled()) {
0N/A wasEnabled = true;
0N/A setEnabled(false);
0N/A }
0N/A } else {
0N/A try {
0N/A wasEnabled = SwingUtilities2.submit(
0N/A new Callable<Boolean>() {
0N/A public Boolean call() throws Exception {
0N/A boolean rv = isEnabled();
0N/A if (rv) {
0N/A setEnabled(false);
0N/A }
0N/A return rv;
0N/A }
0N/A }).get();
0N/A } catch (InterruptedException e) {
0N/A throw new RuntimeException(e);
0N/A } catch (ExecutionException e) {
0N/A Throwable cause = e.getCause();
0N/A if (cause instanceof Error) {
0N/A throw (Error) cause;
0N/A }
0N/A if (cause instanceof RuntimeException) {
0N/A throw (RuntimeException) cause;
0N/A }
0N/A throw new AssertionError(cause);
0N/A }
0N/A }
0N/A
0N/A getDocument().render(futurePrinting);
0N/A
0N/A //enable component
0N/A if (wasEnabled) {
0N/A if (isEventDispatchThread) {
0N/A setEnabled(true);
0N/A } else {
0N/A try {
0N/A SwingUtilities2.submit(
0N/A new Runnable() {
0N/A public void run() {
0N/A setEnabled(true);
0N/A }
0N/A }, null).get();
0N/A } catch (InterruptedException e) {
0N/A throw new RuntimeException(e);
0N/A } catch (ExecutionException e) {
0N/A Throwable cause = e.getCause();
0N/A if (cause instanceof Error) {
0N/A throw (Error) cause;
0N/A }
0N/A if (cause instanceof RuntimeException) {
0N/A throw (RuntimeException) cause;
0N/A }
0N/A throw new AssertionError(cause);
0N/A }
0N/A }
0N/A }
0N/A }
0N/A };
0N/A
0N/A if (! interactive || isHeadless) {
0N/A runnablePrinting.run();
0N/A } else {
0N/A if (isEventDispatchThread) {
0N/A (new Thread(runnablePrinting)).start();
0N/A printingStatus.showModal(true);
0N/A } else {
0N/A printingStatus.showModal(false);
0N/A runnablePrinting.run();
0N/A }
0N/A }
0N/A
0N/A //the printing is done successfully or otherwise.
0N/A //dialog is hidden if needed.
0N/A try {
0N/A futurePrinting.get();
0N/A } catch (InterruptedException e) {
0N/A throw new RuntimeException(e);
0N/A } catch (ExecutionException e) {
0N/A Throwable cause = e.getCause();
0N/A if (cause instanceof PrinterAbortException) {
0N/A if (printingStatus != null
0N/A && printingStatus.isAborted()) {
0N/A return false;
0N/A } else {
0N/A throw (PrinterAbortException) cause;
0N/A }
0N/A } else if (cause instanceof PrinterException) {
0N/A throw (PrinterException) cause;
0N/A } else if (cause instanceof RuntimeException) {
0N/A throw (RuntimeException) cause;
0N/A } else if (cause instanceof Error) {
0N/A throw (Error) cause;
0N/A } else {
0N/A throw new AssertionError(cause);
0N/A }
0N/A }
0N/A return true;
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Returns a {@code Printable} to use for printing the content of this
0N/A * {@code JTextComponent}. The returned {@code Printable} prints
0N/A * the document as it looks on the screen except being reformatted
0N/A * to fit the paper.
0N/A * The returned {@code Printable} can be wrapped inside another
0N/A * {@code Printable} in order to create complex reports and
0N/A * documents.
0N/A *
0N/A *
0N/A * <p>
0N/A * The returned {@code Printable} shares the {@code document} with this
0N/A * {@code JTextComponent}. It is the responsibility of the developer to
0N/A * ensure that the {@code document} is not mutated while this {@code Printable}
0N/A * is used. Printing behavior is undefined when the {@code document} is
0N/A * mutated during printing.
0N/A *
0N/A * <p>
0N/A * Page header and footer text can be added to the output by providing
0N/A * {@code MessageFormat} arguments. The printing code requests
0N/A * {@code Strings} from the formats, providing a single item which may be
0N/A * included in the formatted string: an {@code Integer} representing the
0N/A * current page number.
0N/A *
0N/A * <p>
0N/A * The returned {@code Printable} when printed, formats the
0N/A * document content appropriately for the page size. For correct
0N/A * line wrapping the {@code imageable width} of all pages must be the
0N/A * same. See {@link java.awt.print.PageFormat#getImageableWidth}.
0N/A *
0N/A * <p>
0N/A * This method is thread-safe, although most Swing methods are not. Please
0N/A * see <A
0N/A * HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">
0N/A * How to Use Threads</A> for more information.
0N/A *
0N/A * <p>
0N/A * The returned {@code Printable} can be printed on any thread.
0N/A *
0N/A * <p>
0N/A * This implementation returned {@code Printable} performs all painting on
0N/A * the <i>Event Dispatch Thread</i>, regardless of what thread it is
0N/A * used on.
0N/A *
0N/A * @param headerFormat the text, in {@code MessageFormat}, to be
0N/A * used as the header, or {@code null} for no header
0N/A * @param footerFormat the text, in {@code MessageFormat}, to be
0N/A * used as the footer, or {@code null} for no footer
0N/A * @return a {@code Printable} for use in printing content of this
0N/A * {@code JTextComponent}
0N/A *
0N/A *
0N/A * @see java.awt.print.Printable
0N/A * @see java.awt.print.PageFormat
0N/A * @see javax.swing.text.Document#render(java.lang.Runnable)
0N/A *
0N/A * @since 1.6
0N/A */
0N/A public Printable getPrintable(final MessageFormat headerFormat,
0N/A final MessageFormat footerFormat) {
0N/A return TextComponentPrintable.getPrintable(
0N/A this, headerFormat, footerFormat);
0N/A }
0N/A
0N/A
0N/A/////////////////
0N/A// Accessibility support
0N/A////////////////
0N/A
0N/A
0N/A /**
0N/A * Gets the <code>AccessibleContext</code> associated with this
0N/A * <code>JTextComponent</code>. For text components,
0N/A * the <code>AccessibleContext</code> takes the form of an
0N/A * <code>AccessibleJTextComponent</code>.
0N/A * A new <code>AccessibleJTextComponent</code> instance
0N/A * is created if necessary.
0N/A *
0N/A * @return an <code>AccessibleJTextComponent</code> that serves as the
0N/A * <code>AccessibleContext</code> of this
0N/A * <code>JTextComponent</code>
0N/A */
0N/A public AccessibleContext getAccessibleContext() {
0N/A if (accessibleContext == null) {
0N/A accessibleContext = new AccessibleJTextComponent();
0N/A }
0N/A return accessibleContext;
0N/A }
0N/A
0N/A /**
0N/A * This class implements accessibility support for the
0N/A * <code>JTextComponent</code> class. It provides an implementation of
0N/A * the Java Accessibility API appropriate to menu user-interface elements.
0N/A * <p>
0N/A * <strong>Warning:</strong>
0N/A * Serialized objects of this class will not be compatible with
0N/A * future Swing releases. The current serialization support is
0N/A * appropriate for short term storage or RMI between applications running
0N/A * the same version of Swing. As of 1.4, support for long term storage
0N/A * of all JavaBeans<sup><font size="-2">TM</font></sup>
0N/A * has been added to the <code>java.beans</code> package.
0N/A * Please see {@link java.beans.XMLEncoder}.
0N/A */
0N/A public class AccessibleJTextComponent extends AccessibleJComponent
0N/A implements AccessibleText, CaretListener, DocumentListener,
0N/A AccessibleAction, AccessibleEditableText,
0N/A AccessibleExtendedText {
0N/A
0N/A int caretPos;
0N/A Point oldLocationOnScreen;
0N/A
0N/A /**
0N/A * Constructs an AccessibleJTextComponent. Adds a listener to track
0N/A * caret change.
0N/A */
0N/A public AccessibleJTextComponent() {
0N/A Document doc = JTextComponent.this.getDocument();
0N/A if (doc != null) {
0N/A doc.addDocumentListener(this);
0N/A }
0N/A JTextComponent.this.addCaretListener(this);
0N/A caretPos = getCaretPosition();
0N/A
0N/A try {
0N/A oldLocationOnScreen = getLocationOnScreen();
0N/A } catch (IllegalComponentStateException iae) {
0N/A }
0N/A
0N/A // Fire a ACCESSIBLE_VISIBLE_DATA_PROPERTY PropertyChangeEvent
0N/A // when the text component moves (e.g., when scrolling).
0N/A // Using an anonymous class since making AccessibleJTextComponent
0N/A // implement ComponentListener would be an API change.
0N/A JTextComponent.this.addComponentListener(new ComponentAdapter() {
0N/A
0N/A public void componentMoved(ComponentEvent e) {
0N/A try {
0N/A Point newLocationOnScreen = getLocationOnScreen();
0N/A firePropertyChange(ACCESSIBLE_VISIBLE_DATA_PROPERTY,
0N/A oldLocationOnScreen,
0N/A newLocationOnScreen);
0N/A
0N/A oldLocationOnScreen = newLocationOnScreen;
0N/A } catch (IllegalComponentStateException iae) {
0N/A }
0N/A }
0N/A });
0N/A }
0N/A
0N/A /**
0N/A * Handles caret updates (fire appropriate property change event,
0N/A * which are AccessibleContext.ACCESSIBLE_CARET_PROPERTY and
0N/A * AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY).
0N/A * This keeps track of the dot position internally. When the caret
0N/A * moves, the internal position is updated after firing the event.
0N/A *
0N/A * @param e the CaretEvent
0N/A */
0N/A public void caretUpdate(CaretEvent e) {
0N/A int dot = e.getDot();
0N/A int mark = e.getMark();
0N/A if (caretPos != dot) {
0N/A // the caret moved
0N/A firePropertyChange(ACCESSIBLE_CARET_PROPERTY,
0N/A new Integer(caretPos), new Integer(dot));
0N/A caretPos = dot;
0N/A
0N/A try {
0N/A oldLocationOnScreen = getLocationOnScreen();
0N/A } catch (IllegalComponentStateException iae) {
0N/A }
0N/A }
0N/A if (mark != dot) {
0N/A // there is a selection
0N/A firePropertyChange(ACCESSIBLE_SELECTION_PROPERTY, null,
0N/A getSelectedText());
0N/A }
0N/A }
0N/A
0N/A // DocumentListener methods
0N/A
0N/A /**
0N/A * Handles document insert (fire appropriate property change event
0N/A * which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY).
0N/A * This tracks the changed offset via the event.
0N/A *
0N/A * @param e the DocumentEvent
0N/A */
0N/A public void insertUpdate(DocumentEvent e) {
0N/A final Integer pos = new Integer (e.getOffset());
0N/A if (SwingUtilities.isEventDispatchThread()) {
0N/A firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, null, pos);
0N/A } else {
0N/A Runnable doFire = new Runnable() {
0N/A public void run() {
0N/A firePropertyChange(ACCESSIBLE_TEXT_PROPERTY,
0N/A null, pos);
0N/A }
0N/A };
0N/A SwingUtilities.invokeLater(doFire);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Handles document remove (fire appropriate property change event,
0N/A * which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY).
0N/A * This tracks the changed offset via the event.
0N/A *
0N/A * @param e the DocumentEvent
0N/A */
0N/A public void removeUpdate(DocumentEvent e) {
0N/A final Integer pos = new Integer (e.getOffset());
0N/A if (SwingUtilities.isEventDispatchThread()) {
0N/A firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, null, pos);
0N/A } else {
0N/A Runnable doFire = new Runnable() {
0N/A public void run() {
0N/A firePropertyChange(ACCESSIBLE_TEXT_PROPERTY,
0N/A null, pos);
0N/A }
0N/A };
0N/A SwingUtilities.invokeLater(doFire);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Handles document remove (fire appropriate property change event,
0N/A * which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY).
0N/A * This tracks the changed offset via the event.
0N/A *
0N/A * @param e the DocumentEvent
0N/A */
0N/A public void changedUpdate(DocumentEvent e) {
0N/A final Integer pos = new Integer (e.getOffset());
0N/A if (SwingUtilities.isEventDispatchThread()) {
0N/A firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, null, pos);
0N/A } else {
0N/A Runnable doFire = new Runnable() {
0N/A public void run() {
0N/A firePropertyChange(ACCESSIBLE_TEXT_PROPERTY,
0N/A null, pos);
0N/A }
0N/A };
0N/A SwingUtilities.invokeLater(doFire);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Gets the state set of the JTextComponent.
0N/A * The AccessibleStateSet of an object is composed of a set of
0N/A * unique AccessibleState's. A change in the AccessibleStateSet
0N/A * of an object will cause a PropertyChangeEvent to be fired
0N/A * for the AccessibleContext.ACCESSIBLE_STATE_PROPERTY property.
0N/A *
0N/A * @return an instance of AccessibleStateSet containing the
0N/A * current state set of the object
0N/A * @see AccessibleStateSet
0N/A * @see AccessibleState
0N/A * @see #addPropertyChangeListener
0N/A */
0N/A public AccessibleStateSet getAccessibleStateSet() {
0N/A AccessibleStateSet states = super.getAccessibleStateSet();
0N/A if (JTextComponent.this.isEditable()) {
0N/A states.add(AccessibleState.EDITABLE);
0N/A }
0N/A return states;
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Gets the role of this object.
0N/A *
0N/A * @return an instance of AccessibleRole describing the role of the
0N/A * object (AccessibleRole.TEXT)
0N/A * @see AccessibleRole
0N/A */
0N/A public AccessibleRole getAccessibleRole() {
0N/A return AccessibleRole.TEXT;
0N/A }
0N/A
0N/A /**
0N/A * Get the AccessibleText associated with this object. In the
0N/A * implementation of the Java Accessibility API for this class,
0N/A * return this object, which is responsible for implementing the
0N/A * AccessibleText interface on behalf of itself.
0N/A *
0N/A * @return this object
0N/A */
0N/A public AccessibleText getAccessibleText() {
0N/A return this;
0N/A }
0N/A
0N/A
0N/A // --- interface AccessibleText methods ------------------------
0N/A
0N/A /**
0N/A * Many of these methods are just convenience methods; they
0N/A * just call the equivalent on the parent
0N/A */
0N/A
0N/A /**
0N/A * Given a point in local coordinates, return the zero-based index
0N/A * of the character under that Point. If the point is invalid,
0N/A * this method returns -1.
0N/A *
0N/A * @param p the Point in local coordinates
0N/A * @return the zero-based index of the character under Point p.
0N/A */
0N/A public int getIndexAtPoint(Point p) {
0N/A if (p == null) {
0N/A return -1;
0N/A }
0N/A return JTextComponent.this.viewToModel(p);
0N/A }
0N/A
0N/A /**
0N/A * Gets the editor's drawing rectangle. Stolen
0N/A * from the unfortunately named
0N/A * BasicTextUI.getVisibleEditorRect()
0N/A *
0N/A * @return the bounding box for the root view
0N/A */
0N/A Rectangle getRootEditorRect() {
0N/A Rectangle alloc = JTextComponent.this.getBounds();
0N/A if ((alloc.width > 0) && (alloc.height > 0)) {
0N/A alloc.x = alloc.y = 0;
0N/A Insets insets = JTextComponent.this.getInsets();
0N/A alloc.x += insets.left;
0N/A alloc.y += insets.top;
0N/A alloc.width -= insets.left + insets.right;
0N/A alloc.height -= insets.top + insets.bottom;
0N/A return alloc;
0N/A }
0N/A return null;
0N/A }
0N/A
0N/A /**
0N/A * Determines the bounding box of the character at the given
0N/A * index into the string. The bounds are returned in local
0N/A * coordinates. If the index is invalid a null rectangle
0N/A * is returned.
0N/A *
0N/A * The screen coordinates returned are "unscrolled coordinates"
0N/A * if the JTextComponent is contained in a JScrollPane in which
0N/A * case the resulting rectangle should be composed with the parent
0N/A * coordinates. A good algorithm to use is:
0N/A * <nf>
0N/A * Accessible a:
0N/A * AccessibleText at = a.getAccessibleText();
0N/A * AccessibleComponent ac = a.getAccessibleComponent();
0N/A * Rectangle r = at.getCharacterBounds();
0N/A * Point p = ac.getLocation();
0N/A * r.x += p.x;
0N/A * r.y += p.y;
0N/A * </nf>
0N/A *
0N/A * Note: the JTextComponent must have a valid size (e.g. have
0N/A * been added to a parent container whose ancestor container
0N/A * is a valid top-level window) for this method to be able
0N/A * to return a meaningful (non-null) value.
0N/A *
0N/A * @param i the index into the String >= 0
0N/A * @return the screen coordinates of the character's bounding box
0N/A */
0N/A public Rectangle getCharacterBounds(int i) {
0N/A if (i < 0 || i > model.getLength()-1) {
0N/A return null;
0N/A }
0N/A TextUI ui = getUI();
0N/A if (ui == null) {
0N/A return null;
0N/A }
0N/A Rectangle rect = null;
0N/A Rectangle alloc = getRootEditorRect();
0N/A if (alloc == null) {
0N/A return null;
0N/A }
0N/A if (model instanceof AbstractDocument) {
0N/A ((AbstractDocument)model).readLock();
0N/A }
0N/A try {
0N/A View rootView = ui.getRootView(JTextComponent.this);
0N/A if (rootView != null) {
0N/A rootView.setSize(alloc.width, alloc.height);
0N/A
0N/A Shape bounds = rootView.modelToView(i,
0N/A Position.Bias.Forward, i+1,
0N/A Position.Bias.Backward, alloc);
0N/A
0N/A rect = (bounds instanceof Rectangle) ?
0N/A (Rectangle)bounds : bounds.getBounds();
0N/A
0N/A }
0N/A } catch (BadLocationException e) {
0N/A } finally {
0N/A if (model instanceof AbstractDocument) {
0N/A ((AbstractDocument)model).readUnlock();
0N/A }
0N/A }
0N/A return rect;
0N/A }
0N/A
0N/A /**
0N/A * Returns the number of characters (valid indices)
0N/A *
0N/A * @return the number of characters >= 0
0N/A */
0N/A public int getCharCount() {
0N/A return model.getLength();
0N/A }
0N/A
0N/A /**
0N/A * Returns the zero-based offset of the caret.
0N/A *
0N/A * Note: The character to the right of the caret will have the
0N/A * same index value as the offset (the caret is between
0N/A * two characters).
0N/A *
0N/A * @return the zero-based offset of the caret.
0N/A */
0N/A public int getCaretPosition() {
0N/A return JTextComponent.this.getCaretPosition();
0N/A }
0N/A
0N/A /**
0N/A * Returns the AttributeSet for a given character (at a given index).
0N/A *
0N/A * @param i the zero-based index into the text
0N/A * @return the AttributeSet of the character
0N/A */
0N/A public AttributeSet getCharacterAttribute(int i) {
0N/A Element e = null;
0N/A if (model instanceof AbstractDocument) {
0N/A ((AbstractDocument)model).readLock();
0N/A }
0N/A try {
0N/A for (e = model.getDefaultRootElement(); ! e.isLeaf(); ) {
0N/A int index = e.getElementIndex(i);
0N/A e = e.getElement(index);
0N/A }
0N/A } finally {
0N/A if (model instanceof AbstractDocument) {
0N/A ((AbstractDocument)model).readUnlock();
0N/A }
0N/A }
0N/A return e.getAttributes();
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Returns the start offset within the selected text.
0N/A * If there is no selection, but there is
0N/A * a caret, the start and end offsets will be the same.
0N/A * Return 0 if the text is empty, or the caret position
0N/A * if no selection.
0N/A *
0N/A * @return the index into the text of the start of the selection >= 0
0N/A */
0N/A public int getSelectionStart() {
0N/A return JTextComponent.this.getSelectionStart();
0N/A }
0N/A
0N/A /**
0N/A * Returns the end offset within the selected text.
0N/A * If there is no selection, but there is
0N/A * a caret, the start and end offsets will be the same.
0N/A * Return 0 if the text is empty, or the caret position
0N/A * if no selection.
0N/A *
0N/A * @return the index into teh text of the end of the selection >= 0
0N/A */
0N/A public int getSelectionEnd() {
0N/A return JTextComponent.this.getSelectionEnd();
0N/A }
0N/A
0N/A /**
0N/A * Returns the portion of the text that is selected.
0N/A *
0N/A * @return the text, null if no selection
0N/A */
0N/A public String getSelectedText() {
0N/A return JTextComponent.this.getSelectedText();
0N/A }
0N/A
0N/A /**
0N/A * IndexedSegment extends Segment adding the offset into the
0N/A * the model the <code>Segment</code> was asked for.
0N/A */
0N/A private class IndexedSegment extends Segment {
0N/A /**
0N/A * Offset into the model that the position represents.
0N/A */
0N/A public int modelOffset;
0N/A }
0N/A
0N/A
0N/A // TIGER - 4170173
0N/A /**
0N/A * Returns the String at a given index. Whitespace
0N/A * between words is treated as a word.
0N/A *
0N/A * @param part the CHARACTER, WORD, or SENTENCE to retrieve
0N/A * @param index an index within the text
0N/A * @return the letter, word, or sentence.
0N/A *
0N/A */
0N/A public String getAtIndex(int part, int index) {
0N/A return getAtIndex(part, index, 0);
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Returns the String after a given index. Whitespace
0N/A * between words is treated as a word.
0N/A *
0N/A * @param part the CHARACTER, WORD, or SENTENCE to retrieve
0N/A * @param index an index within the text
0N/A * @return the letter, word, or sentence.
0N/A */
0N/A public String getAfterIndex(int part, int index) {
0N/A return getAtIndex(part, index, 1);
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Returns the String before a given index. Whitespace
0N/A * between words is treated a word.
0N/A *
0N/A * @param part the CHARACTER, WORD, or SENTENCE to retrieve
0N/A * @param index an index within the text
0N/A * @return the letter, word, or sentence.
0N/A */
0N/A public String getBeforeIndex(int part, int index) {
0N/A return getAtIndex(part, index, -1);
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Gets the word, sentence, or character at <code>index</code>.
0N/A * If <code>direction</code> is non-null this will find the
0N/A * next/previous word/sentence/character.
0N/A */
0N/A private String getAtIndex(int part, int index, int direction) {
0N/A if (model instanceof AbstractDocument) {
0N/A ((AbstractDocument)model).readLock();
0N/A }
0N/A try {
0N/A if (index < 0 || index >= model.getLength()) {
0N/A return null;
0N/A }
0N/A switch (part) {
0N/A case AccessibleText.CHARACTER:
0N/A if (index + direction < model.getLength() &&
0N/A index + direction >= 0) {
0N/A return model.getText(index + direction, 1);
0N/A }
0N/A break;
0N/A
0N/A
0N/A case AccessibleText.WORD:
0N/A case AccessibleText.SENTENCE:
0N/A IndexedSegment seg = getSegmentAt(part, index);
0N/A if (seg != null) {
0N/A if (direction != 0) {
0N/A int next;
0N/A
0N/A
0N/A if (direction < 0) {
0N/A next = seg.modelOffset - 1;
0N/A }
0N/A else {
0N/A next = seg.modelOffset + direction * seg.count;
0N/A }
0N/A if (next >= 0 && next <= model.getLength()) {
0N/A seg = getSegmentAt(part, next);
0N/A }
0N/A else {
0N/A seg = null;
0N/A }
0N/A }
0N/A if (seg != null) {
0N/A return new String(seg.array, seg.offset,
0N/A seg.count);
0N/A }
0N/A }
0N/A break;
0N/A
0N/A
0N/A default:
0N/A break;
0N/A }
0N/A } catch (BadLocationException e) {
0N/A } finally {
0N/A if (model instanceof AbstractDocument) {
0N/A ((AbstractDocument)model).readUnlock();
0N/A }
0N/A }
0N/A return null;
0N/A }
0N/A
0N/A
0N/A /*
0N/A * Returns the paragraph element for the specified index.
0N/A */
0N/A private Element getParagraphElement(int index) {
0N/A if (model instanceof PlainDocument ) {
0N/A PlainDocument sdoc = (PlainDocument)model;
0N/A return sdoc.getParagraphElement(index);
0N/A } else if (model instanceof StyledDocument) {
0N/A StyledDocument sdoc = (StyledDocument)model;
0N/A return sdoc.getParagraphElement(index);
0N/A } else {
611N/A Element para;
0N/A for (para = model.getDefaultRootElement(); ! para.isLeaf(); ) {
0N/A int pos = para.getElementIndex(index);
0N/A para = para.getElement(pos);
0N/A }
0N/A if (para == null) {
0N/A return null;
0N/A }
0N/A return para.getParentElement();
0N/A }
0N/A }
0N/A
0N/A /*
0N/A * Returns a <code>Segment</code> containing the paragraph text
0N/A * at <code>index</code>, or null if <code>index</code> isn't
0N/A * valid.
0N/A */
0N/A private IndexedSegment getParagraphElementText(int index)
0N/A throws BadLocationException {
0N/A Element para = getParagraphElement(index);
0N/A
0N/A
0N/A if (para != null) {
0N/A IndexedSegment segment = new IndexedSegment();
0N/A try {
0N/A int length = para.getEndOffset() - para.getStartOffset();
0N/A model.getText(para.getStartOffset(), length, segment);
0N/A } catch (BadLocationException e) {
0N/A return null;
0N/A }
0N/A segment.modelOffset = para.getStartOffset();
0N/A return segment;
0N/A }
0N/A return null;
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Returns the Segment at <code>index</code> representing either
0N/A * the paragraph or sentence as identified by <code>part</code>, or
0N/A * null if a valid paragraph/sentence can't be found. The offset
0N/A * will point to the start of the word/sentence in the array, and
0N/A * the modelOffset will point to the location of the word/sentence
0N/A * in the model.
0N/A */
0N/A private IndexedSegment getSegmentAt(int part, int index) throws
0N/A BadLocationException {
0N/A IndexedSegment seg = getParagraphElementText(index);
0N/A if (seg == null) {
0N/A return null;
0N/A }
0N/A BreakIterator iterator;
0N/A switch (part) {
0N/A case AccessibleText.WORD:
0N/A iterator = BreakIterator.getWordInstance(getLocale());
0N/A break;
0N/A case AccessibleText.SENTENCE:
0N/A iterator = BreakIterator.getSentenceInstance(getLocale());
0N/A break;
0N/A default:
0N/A return null;
0N/A }
0N/A seg.first();
0N/A iterator.setText(seg);
0N/A int end = iterator.following(index - seg.modelOffset + seg.offset);
0N/A if (end == BreakIterator.DONE) {
0N/A return null;
0N/A }
0N/A if (end > seg.offset + seg.count) {
0N/A return null;
0N/A }
0N/A int begin = iterator.previous();
0N/A if (begin == BreakIterator.DONE ||
0N/A begin >= seg.offset + seg.count) {
0N/A return null;
0N/A }
0N/A seg.modelOffset = seg.modelOffset + begin - seg.offset;
0N/A seg.offset = begin;
0N/A seg.count = end - begin;
0N/A return seg;
0N/A }
0N/A
0N/A // begin AccessibleEditableText methods -----
0N/A
0N/A /**
0N/A * Returns the AccessibleEditableText interface for
0N/A * this text component.
0N/A *
0N/A * @return the AccessibleEditableText interface
0N/A * @since 1.4
0N/A */
0N/A public AccessibleEditableText getAccessibleEditableText() {
0N/A return this;
0N/A }
0N/A
0N/A /**
0N/A * Sets the text contents to the specified string.
0N/A *
0N/A * @param s the string to set the text contents
0N/A * @since 1.4
0N/A */
0N/A public void setTextContents(String s) {
0N/A JTextComponent.this.setText(s);
0N/A }
0N/A
0N/A /**
0N/A * Inserts the specified string at the given index
0N/A *
0N/A * @param index the index in the text where the string will
0N/A * be inserted
0N/A * @param s the string to insert in the text
0N/A * @since 1.4
0N/A */
0N/A public void insertTextAtIndex(int index, String s) {
0N/A Document doc = JTextComponent.this.getDocument();
0N/A if (doc != null) {
0N/A try {
0N/A if (s != null && s.length() > 0) {
0N/A boolean composedTextSaved = saveComposedText(index);
0N/A doc.insertString(index, s, null);
0N/A if (composedTextSaved) {
0N/A restoreComposedText();
0N/A }
0N/A }
0N/A } catch (BadLocationException e) {
0N/A UIManager.getLookAndFeel().provideErrorFeedback(JTextComponent.this);
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns the text string between two indices.
0N/A *
0N/A * @param startIndex the starting index in the text
0N/A * @param endIndex the ending index in the text
0N/A * @return the text string between the indices
0N/A * @since 1.4
0N/A */
0N/A public String getTextRange(int startIndex, int endIndex) {
0N/A String txt = null;
0N/A int p0 = Math.min(startIndex, endIndex);
0N/A int p1 = Math.max(startIndex, endIndex);
0N/A if (p0 != p1) {
0N/A try {
0N/A Document doc = JTextComponent.this.getDocument();
0N/A txt = doc.getText(p0, p1 - p0);
0N/A } catch (BadLocationException e) {
0N/A throw new IllegalArgumentException(e.getMessage());
0N/A }
0N/A }
0N/A return txt;
0N/A }
0N/A
0N/A /**
0N/A * Deletes the text between two indices
0N/A *
0N/A * @param startIndex the starting index in the text
0N/A * @param endIndex the ending index in the text
0N/A * @since 1.4
0N/A */
0N/A public void delete(int startIndex, int endIndex) {
0N/A if (isEditable() && isEnabled()) {
0N/A try {
0N/A int p0 = Math.min(startIndex, endIndex);
0N/A int p1 = Math.max(startIndex, endIndex);
0N/A if (p0 != p1) {
0N/A Document doc = getDocument();
0N/A doc.remove(p0, p1 - p0);
0N/A }
0N/A } catch (BadLocationException e) {
0N/A }
0N/A } else {
0N/A UIManager.getLookAndFeel().provideErrorFeedback(JTextComponent.this);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Cuts the text between two indices into the system clipboard.
0N/A *
0N/A * @param startIndex the starting index in the text
0N/A * @param endIndex the ending index in the text
0N/A * @since 1.4
0N/A */
0N/A public void cut(int startIndex, int endIndex) {
0N/A selectText(startIndex, endIndex);
0N/A JTextComponent.this.cut();
0N/A }
0N/A
0N/A /**
0N/A * Pastes the text from the system clipboard into the text
0N/A * starting at the specified index.
0N/A *
0N/A * @param startIndex the starting index in the text
0N/A * @since 1.4
0N/A */
0N/A public void paste(int startIndex) {
0N/A setCaretPosition(startIndex);
0N/A JTextComponent.this.paste();
0N/A }
0N/A
0N/A /**
0N/A * Replaces the text between two indices with the specified
0N/A * string.
0N/A *
0N/A * @param startIndex the starting index in the text
0N/A * @param endIndex the ending index in the text
0N/A * @param s the string to replace the text between two indices
0N/A * @since 1.4
0N/A */
0N/A public void replaceText(int startIndex, int endIndex, String s) {
0N/A selectText(startIndex, endIndex);
0N/A JTextComponent.this.replaceSelection(s);
0N/A }
0N/A
0N/A /**
0N/A * Selects the text between two indices.
0N/A *
0N/A * @param startIndex the starting index in the text
0N/A * @param endIndex the ending index in the text
0N/A * @since 1.4
0N/A */
0N/A public void selectText(int startIndex, int endIndex) {
0N/A JTextComponent.this.select(startIndex, endIndex);
0N/A }
0N/A
0N/A /**
0N/A * Sets attributes for the text between two indices.
0N/A *
0N/A * @param startIndex the starting index in the text
0N/A * @param endIndex the ending index in the text
0N/A * @param as the attribute set
0N/A * @see AttributeSet
0N/A * @since 1.4
0N/A */
0N/A public void setAttributes(int startIndex, int endIndex,
0N/A AttributeSet as) {
0N/A
0N/A // Fixes bug 4487492
0N/A Document doc = JTextComponent.this.getDocument();
0N/A if (doc != null && doc instanceof StyledDocument) {
0N/A StyledDocument sDoc = (StyledDocument)doc;
0N/A int offset = startIndex;
0N/A int length = endIndex - startIndex;
0N/A sDoc.setCharacterAttributes(offset, length, as, true);
0N/A }
0N/A }
0N/A
0N/A // ----- end AccessibleEditableText methods
0N/A
0N/A
0N/A // ----- begin AccessibleExtendedText methods
0N/A
0N/A// Probably should replace the helper method getAtIndex() to return
0N/A// instead an AccessibleTextSequence also for LINE & ATTRIBUTE_RUN
0N/A// and then make the AccessibleText methods get[At|After|Before]Point
0N/A// call this new method instead and return only the string portion
0N/A
0N/A /**
0N/A * Returns the AccessibleTextSequence at a given <code>index</code>.
0N/A * If <code>direction</code> is non-null this will find the
0N/A * next/previous word/sentence/character.
0N/A *
0N/A * @param part the <code>CHARACTER</code>, <code>WORD</code>,
0N/A * <code>SENTENCE</code>, <code>LINE</code> or
0N/A * <code>ATTRIBUTE_RUN</code> to retrieve
0N/A * @param index an index within the text
0N/A * @param direction is either -1, 0, or 1
0N/A * @return an <code>AccessibleTextSequence</code> specifying the text
0N/A * if <code>part</code> and <code>index</code> are valid. Otherwise,
0N/A * <code>null</code> is returned.
0N/A *
0N/A * @see javax.accessibility.AccessibleText#CHARACTER
0N/A * @see javax.accessibility.AccessibleText#WORD
0N/A * @see javax.accessibility.AccessibleText#SENTENCE
0N/A * @see javax.accessibility.AccessibleExtendedText#LINE
0N/A * @see javax.accessibility.AccessibleExtendedText#ATTRIBUTE_RUN
0N/A *
0N/A * @since 1.6
0N/A */
0N/A private AccessibleTextSequence getSequenceAtIndex(int part,
0N/A int index, int direction) {
0N/A if (index < 0 || index >= model.getLength()) {
0N/A return null;
0N/A }
0N/A if (direction < -1 || direction > 1) {
0N/A return null; // direction must be 1, 0, or -1
0N/A }
0N/A
0N/A switch (part) {
0N/A case AccessibleText.CHARACTER:
0N/A if (model instanceof AbstractDocument) {
0N/A ((AbstractDocument)model).readLock();
0N/A }
0N/A AccessibleTextSequence charSequence = null;
0N/A try {
0N/A if (index + direction < model.getLength() &&
0N/A index + direction >= 0) {
0N/A charSequence =
0N/A new AccessibleTextSequence(index + direction,
0N/A index + direction + 1,
0N/A model.getText(index + direction, 1));
0N/A }
0N/A
0N/A } catch (BadLocationException e) {
0N/A // we are intentionally silent; our contract says we return
0N/A // null if there is any failure in this method
0N/A } finally {
0N/A if (model instanceof AbstractDocument) {
0N/A ((AbstractDocument)model).readUnlock();
0N/A }
0N/A }
0N/A return charSequence;
0N/A
0N/A case AccessibleText.WORD:
0N/A case AccessibleText.SENTENCE:
0N/A if (model instanceof AbstractDocument) {
0N/A ((AbstractDocument)model).readLock();
0N/A }
0N/A AccessibleTextSequence rangeSequence = null;
0N/A try {
0N/A IndexedSegment seg = getSegmentAt(part, index);
0N/A if (seg != null) {
0N/A if (direction != 0) {
0N/A int next;
0N/A
0N/A if (direction < 0) {
0N/A next = seg.modelOffset - 1;
0N/A }
0N/A else {
0N/A next = seg.modelOffset + seg.count;
0N/A }
0N/A if (next >= 0 && next <= model.getLength()) {
0N/A seg = getSegmentAt(part, next);
0N/A }
0N/A else {
0N/A seg = null;
0N/A }
0N/A }
0N/A if (seg != null &&
0N/A (seg.offset + seg.count) <= model.getLength()) {
0N/A rangeSequence =
0N/A new AccessibleTextSequence (seg.offset,
0N/A seg.offset + seg.count,
0N/A new String(seg.array, seg.offset, seg.count));
0N/A } // else we leave rangeSequence set to null
0N/A }
0N/A } catch(BadLocationException e) {
0N/A // we are intentionally silent; our contract says we return
0N/A // null if there is any failure in this method
0N/A } finally {
0N/A if (model instanceof AbstractDocument) {
0N/A ((AbstractDocument)model).readUnlock();
0N/A }
0N/A }
0N/A return rangeSequence;
0N/A
0N/A case AccessibleExtendedText.LINE:
0N/A AccessibleTextSequence lineSequence = null;
0N/A if (model instanceof AbstractDocument) {
0N/A ((AbstractDocument)model).readLock();
0N/A }
0N/A try {
0N/A int startIndex =
0N/A Utilities.getRowStart(JTextComponent.this, index);
0N/A int endIndex =
0N/A Utilities.getRowEnd(JTextComponent.this, index);
0N/A if (startIndex >= 0 && endIndex >= startIndex) {
0N/A if (direction == 0) {
0N/A lineSequence =
0N/A new AccessibleTextSequence(startIndex, endIndex,
0N/A model.getText(startIndex,
0N/A endIndex - startIndex + 1));
0N/A } else if (direction == -1 && startIndex > 0) {
0N/A endIndex =
0N/A Utilities.getRowEnd(JTextComponent.this,
0N/A startIndex - 1);
0N/A startIndex =
0N/A Utilities.getRowStart(JTextComponent.this,
0N/A startIndex - 1);
0N/A if (startIndex >= 0 && endIndex >= startIndex) {
0N/A lineSequence =
0N/A new AccessibleTextSequence(startIndex,
0N/A endIndex,
0N/A model.getText(startIndex,
0N/A endIndex - startIndex + 1));
0N/A }
0N/A } else if (direction == 1 &&
0N/A endIndex < model.getLength()) {
0N/A startIndex =
0N/A Utilities.getRowStart(JTextComponent.this,
0N/A endIndex + 1);
0N/A endIndex =
0N/A Utilities.getRowEnd(JTextComponent.this,
0N/A endIndex + 1);
0N/A if (startIndex >= 0 && endIndex >= startIndex) {
0N/A lineSequence =
0N/A new AccessibleTextSequence(startIndex,
0N/A endIndex, model.getText(startIndex,
0N/A endIndex - startIndex + 1));
0N/A }
0N/A }
0N/A // already validated 'direction' above...
0N/A }
0N/A } catch(BadLocationException e) {
0N/A // we are intentionally silent; our contract says we return
0N/A // null if there is any failure in this method
0N/A } finally {
0N/A if (model instanceof AbstractDocument) {
0N/A ((AbstractDocument)model).readUnlock();
0N/A }
0N/A }
0N/A return lineSequence;
0N/A
0N/A case AccessibleExtendedText.ATTRIBUTE_RUN:
0N/A // assumptions: (1) that all characters in a single element
0N/A // share the same attribute set; (2) that adjacent elements
0N/A // *may* share the same attribute set
0N/A
0N/A int attributeRunStartIndex, attributeRunEndIndex;
0N/A String runText = null;
0N/A if (model instanceof AbstractDocument) {
0N/A ((AbstractDocument)model).readLock();
0N/A }
0N/A
0N/A try {
0N/A attributeRunStartIndex = attributeRunEndIndex =
0N/A Integer.MIN_VALUE;
0N/A int tempIndex = index;
0N/A switch (direction) {
0N/A case -1:
0N/A // going backwards, so find left edge of this run -
0N/A // that'll be the end of the previous run
0N/A // (off-by-one counting)
0N/A attributeRunEndIndex = getRunEdge(index, direction);
0N/A // now set ourselves up to find the left edge of the
0N/A // prev. run
0N/A tempIndex = attributeRunEndIndex - 1;
0N/A break;
0N/A case 1:
0N/A // going forward, so find right edge of this run -
0N/A // that'll be the start of the next run
0N/A // (off-by-one counting)
0N/A attributeRunStartIndex = getRunEdge(index, direction);
0N/A // now set ourselves up to find the right edge of the
0N/A // next run
0N/A tempIndex = attributeRunStartIndex;
0N/A break;
0N/A case 0:
0N/A // interested in the current run, so nothing special to
0N/A // set up in advance...
0N/A break;
0N/A default:
0N/A // only those three values of direction allowed...
0N/A throw new AssertionError(direction);
0N/A }
0N/A
0N/A // set the unset edge; if neither set then we're getting
0N/A // both edges of the current run around our 'index'
0N/A attributeRunStartIndex =
0N/A (attributeRunStartIndex != Integer.MIN_VALUE) ?
0N/A attributeRunStartIndex : getRunEdge(tempIndex, -1);
0N/A attributeRunEndIndex =
0N/A (attributeRunEndIndex != Integer.MIN_VALUE) ?
0N/A attributeRunEndIndex : getRunEdge(tempIndex, 1);
0N/A
0N/A runText = model.getText(attributeRunStartIndex,
0N/A attributeRunEndIndex -
0N/A attributeRunStartIndex);
0N/A } catch (BadLocationException e) {
0N/A // we are intentionally silent; our contract says we return
0N/A // null if there is any failure in this method
0N/A return null;
0N/A } finally {
0N/A if (model instanceof AbstractDocument) {
0N/A ((AbstractDocument)model).readUnlock();
0N/A }
0N/A }
0N/A return new AccessibleTextSequence(attributeRunStartIndex,
0N/A attributeRunEndIndex,
0N/A runText);
0N/A
0N/A default:
0N/A break;
0N/A }
0N/A return null;
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Starting at text position <code>index</code>, and going in
0N/A * <code>direction</code>, return the edge of run that shares the
0N/A * same <code>AttributeSet</code> and parent element as those at
0N/A * <code>index</code>.
0N/A *
0N/A * Note: we assume the document is already locked...
0N/A */
0N/A private int getRunEdge(int index, int direction) throws
0N/A BadLocationException {
0N/A if (index < 0 || index >= model.getLength()) {
0N/A throw new BadLocationException("Location out of bounds", index);
0N/A }
0N/A // locate the Element at index
611N/A Element indexElement;
0N/A // locate the Element at our index/offset
0N/A int elementIndex = -1; // test for initialization
0N/A for (indexElement = model.getDefaultRootElement();
0N/A ! indexElement.isLeaf(); ) {
0N/A elementIndex = indexElement.getElementIndex(index);
0N/A indexElement = indexElement.getElement(elementIndex);
0N/A }
0N/A if (elementIndex == -1) {
0N/A throw new AssertionError(index);
0N/A }
0N/A // cache the AttributeSet and parentElement atindex
0N/A AttributeSet indexAS = indexElement.getAttributes();
0N/A Element parent = indexElement.getParentElement();
0N/A
0N/A // find the first Element before/after ours w/the same AttributeSet
0N/A // if we are already at edge of the first element in our parent
0N/A // then return that edge
611N/A Element edgeElement;
0N/A switch (direction) {
0N/A case -1:
0N/A case 1:
0N/A int edgeElementIndex = elementIndex;
0N/A int elementCount = parent.getElementCount();
0N/A while ((edgeElementIndex + direction) > 0 &&
0N/A ((edgeElementIndex + direction) < elementCount) &&
0N/A parent.getElement(edgeElementIndex
0N/A + direction).getAttributes().isEqual(indexAS)) {
0N/A edgeElementIndex += direction;
0N/A }
0N/A edgeElement = parent.getElement(edgeElementIndex);
0N/A break;
0N/A default:
0N/A throw new AssertionError(direction);
0N/A }
0N/A switch (direction) {
0N/A case -1:
0N/A return edgeElement.getStartOffset();
0N/A case 1:
0N/A return edgeElement.getEndOffset();
0N/A default:
0N/A // we already caught this case earlier; this is to satisfy
0N/A // the compiler...
0N/A return Integer.MIN_VALUE;
0N/A }
0N/A }
0N/A
0N/A // getTextRange() not needed; defined in AccessibleEditableText
0N/A
0N/A /**
0N/A * Returns the <code>AccessibleTextSequence</code> at a given
0N/A * <code>index</code>.
0N/A *
0N/A * @param part the <code>CHARACTER</code>, <code>WORD</code>,
0N/A * <code>SENTENCE</code>, <code>LINE</code> or
0N/A * <code>ATTRIBUTE_RUN</code> to retrieve
0N/A * @param index an index within the text
0N/A * @return an <code>AccessibleTextSequence</code> specifying the text if
0N/A * <code>part</code> and <code>index</code> are valid. Otherwise,
0N/A * <code>null</code> is returned
0N/A *
0N/A * @see javax.accessibility.AccessibleText#CHARACTER
0N/A * @see javax.accessibility.AccessibleText#WORD
0N/A * @see javax.accessibility.AccessibleText#SENTENCE
0N/A * @see javax.accessibility.AccessibleExtendedText#LINE
0N/A * @see javax.accessibility.AccessibleExtendedText#ATTRIBUTE_RUN
0N/A *
0N/A * @since 1.6
0N/A */
0N/A public AccessibleTextSequence getTextSequenceAt(int part, int index) {
0N/A return getSequenceAtIndex(part, index, 0);
0N/A }
0N/A
0N/A /**
0N/A * Returns the <code>AccessibleTextSequence</code> after a given
0N/A * <code>index</code>.
0N/A *
0N/A * @param part the <code>CHARACTER</code>, <code>WORD</code>,
0N/A * <code>SENTENCE</code>, <code>LINE</code> or
0N/A * <code>ATTRIBUTE_RUN</code> to retrieve
0N/A * @param index an index within the text
0N/A * @return an <code>AccessibleTextSequence</code> specifying the text
0N/A * if <code>part</code> and <code>index</code> are valid. Otherwise,
0N/A * <code>null</code> is returned
0N/A *
0N/A * @see javax.accessibility.AccessibleText#CHARACTER
0N/A * @see javax.accessibility.AccessibleText#WORD
0N/A * @see javax.accessibility.AccessibleText#SENTENCE
0N/A * @see javax.accessibility.AccessibleExtendedText#LINE
0N/A * @see javax.accessibility.AccessibleExtendedText#ATTRIBUTE_RUN
0N/A *
0N/A * @since 1.6
0N/A */
0N/A public AccessibleTextSequence getTextSequenceAfter(int part, int index) {
0N/A return getSequenceAtIndex(part, index, 1);
0N/A }
0N/A
0N/A /**
0N/A * Returns the <code>AccessibleTextSequence</code> before a given
0N/A * <code>index</code>.
0N/A *
0N/A * @param part the <code>CHARACTER</code>, <code>WORD</code>,
0N/A * <code>SENTENCE</code>, <code>LINE</code> or
0N/A * <code>ATTRIBUTE_RUN</code> to retrieve
0N/A * @param index an index within the text
0N/A * @return an <code>AccessibleTextSequence</code> specifying the text
0N/A * if <code>part</code> and <code>index</code> are valid. Otherwise,
0N/A * <code>null</code> is returned
0N/A *
0N/A * @see javax.accessibility.AccessibleText#CHARACTER
0N/A * @see javax.accessibility.AccessibleText#WORD
0N/A * @see javax.accessibility.AccessibleText#SENTENCE
0N/A * @see javax.accessibility.AccessibleExtendedText#LINE
0N/A * @see javax.accessibility.AccessibleExtendedText#ATTRIBUTE_RUN
0N/A *
0N/A * @since 1.6
0N/A */
0N/A public AccessibleTextSequence getTextSequenceBefore(int part, int index) {
0N/A return getSequenceAtIndex(part, index, -1);
0N/A }
0N/A
0N/A /**
0N/A * Returns the <code>Rectangle</code> enclosing the text between
0N/A * two indicies.
0N/A *
0N/A * @param startIndex the start index in the text
0N/A * @param endIndex the end index in the text
0N/A * @return the bounding rectangle of the text if the indices are valid.
0N/A * Otherwise, <code>null</code> is returned
0N/A *
0N/A * @since 1.6
0N/A */
0N/A public Rectangle getTextBounds(int startIndex, int endIndex) {
0N/A if (startIndex < 0 || startIndex > model.getLength()-1 ||
0N/A endIndex < 0 || endIndex > model.getLength()-1 ||
0N/A startIndex > endIndex) {
0N/A return null;
0N/A }
0N/A TextUI ui = getUI();
0N/A if (ui == null) {
0N/A return null;
0N/A }
0N/A Rectangle rect = null;
0N/A Rectangle alloc = getRootEditorRect();
0N/A if (alloc == null) {
0N/A return null;
0N/A }
0N/A if (model instanceof AbstractDocument) {
0N/A ((AbstractDocument)model).readLock();
0N/A }
0N/A try {
0N/A View rootView = ui.getRootView(JTextComponent.this);
0N/A if (rootView != null) {
0N/A Shape bounds = rootView.modelToView(startIndex,
0N/A Position.Bias.Forward, endIndex,
0N/A Position.Bias.Backward, alloc);
0N/A
0N/A rect = (bounds instanceof Rectangle) ?
0N/A (Rectangle)bounds : bounds.getBounds();
0N/A
0N/A }
0N/A } catch (BadLocationException e) {
0N/A } finally {
0N/A if (model instanceof AbstractDocument) {
0N/A ((AbstractDocument)model).readUnlock();
0N/A }
0N/A }
0N/A return rect;
0N/A }
0N/A
0N/A // ----- end AccessibleExtendedText methods
0N/A
0N/A
0N/A // --- interface AccessibleAction methods ------------------------
0N/A
0N/A public AccessibleAction getAccessibleAction() {
0N/A return this;
0N/A }
0N/A
0N/A /**
0N/A * Returns the number of accessible actions available in this object
0N/A * If there are more than one, the first one is considered the
0N/A * "default" action of the object.
0N/A *
0N/A * @return the zero-based number of Actions in this object
0N/A * @since 1.4
0N/A */
0N/A public int getAccessibleActionCount() {
0N/A Action [] actions = JTextComponent.this.getActions();
0N/A return actions.length;
0N/A }
0N/A
0N/A /**
0N/A * Returns a description of the specified action of the object.
0N/A *
0N/A * @param i zero-based index of the actions
0N/A * @return a String description of the action
0N/A * @see #getAccessibleActionCount
0N/A * @since 1.4
0N/A */
0N/A public String getAccessibleActionDescription(int i) {
0N/A Action [] actions = JTextComponent.this.getActions();
0N/A if (i < 0 || i >= actions.length) {
0N/A return null;
0N/A }
0N/A return (String)actions[i].getValue(Action.NAME);
0N/A }
0N/A
0N/A /**
0N/A * Performs the specified Action on the object
0N/A *
0N/A * @param i zero-based index of actions
0N/A * @return true if the action was performed; otherwise false.
0N/A * @see #getAccessibleActionCount
0N/A * @since 1.4
0N/A */
0N/A public boolean doAccessibleAction(int i) {
0N/A Action [] actions = JTextComponent.this.getActions();
0N/A if (i < 0 || i >= actions.length) {
0N/A return false;
0N/A }
0N/A ActionEvent ae =
0N/A new ActionEvent(JTextComponent.this,
0N/A ActionEvent.ACTION_PERFORMED, null,
0N/A EventQueue.getMostRecentEventTime(),
0N/A getCurrentEventModifiers());
0N/A actions[i].actionPerformed(ae);
0N/A return true;
0N/A }
0N/A
0N/A // ----- end AccessibleAction methods
0N/A
0N/A
0N/A }
0N/A
0N/A
0N/A // --- serialization ---------------------------------------------
0N/A
0N/A private void readObject(ObjectInputStream s)
0N/A throws IOException, ClassNotFoundException
0N/A {
0N/A s.defaultReadObject();
0N/A caretEvent = new MutableCaretEvent(this);
0N/A addMouseListener(caretEvent);
0N/A addFocusListener(caretEvent);
0N/A }
0N/A
0N/A // --- member variables ----------------------------------
0N/A
0N/A /**
0N/A * The document model.
0N/A */
0N/A private Document model;
0N/A
0N/A /**
0N/A * The caret used to display the insert position
0N/A * and navigate throughout the document.
0N/A *
0N/A * PENDING(prinz)
0N/A * This should be serializable, default installed
0N/A * by UI.
0N/A */
0N/A private transient Caret caret;
0N/A
0N/A /**
0N/A * Object responsible for restricting the cursor navigation.
0N/A */
0N/A private NavigationFilter navigationFilter;
0N/A
0N/A /**
0N/A * The object responsible for managing highlights.
0N/A *
0N/A * PENDING(prinz)
0N/A * This should be serializable, default installed
0N/A * by UI.
0N/A */
0N/A private transient Highlighter highlighter;
0N/A
0N/A /**
0N/A * The current key bindings in effect.
0N/A *
0N/A * PENDING(prinz)
0N/A * This should be serializable, default installed
0N/A * by UI.
0N/A */
0N/A private transient Keymap keymap;
0N/A
0N/A private transient MutableCaretEvent caretEvent;
0N/A private Color caretColor;
0N/A private Color selectionColor;
0N/A private Color selectedTextColor;
0N/A private Color disabledTextColor;
0N/A private boolean editable;
0N/A private Insets margin;
0N/A private char focusAccelerator;
0N/A private boolean dragEnabled;
0N/A
0N/A /**
0N/A * The drop mode for this component.
0N/A */
0N/A private DropMode dropMode = DropMode.USE_SELECTION;
0N/A
0N/A /**
0N/A * The drop location.
0N/A */
0N/A private transient DropLocation dropLocation;
0N/A
0N/A /**
0N/A * Represents a drop location for <code>JTextComponent</code>s.
0N/A *
0N/A * @see #getDropLocation
0N/A * @since 1.6
0N/A */
0N/A public static final class DropLocation extends TransferHandler.DropLocation {
0N/A private final int index;
0N/A private final Position.Bias bias;
0N/A
0N/A private DropLocation(Point p, int index, Position.Bias bias) {
0N/A super(p);
0N/A this.index = index;
0N/A this.bias = bias;
0N/A }
0N/A
0N/A /**
0N/A * Returns the index where dropped data should be inserted into the
0N/A * associated component. This index represents a position between
0N/A * characters, as would be interpreted by a caret.
0N/A *
0N/A * @return the drop index
0N/A */
0N/A public int getIndex() {
0N/A return index;
0N/A }
0N/A
0N/A /**
0N/A * Returns the bias for the drop index.
0N/A *
0N/A * @return the drop bias
0N/A */
0N/A public Position.Bias getBias() {
0N/A return bias;
0N/A }
0N/A
0N/A /**
0N/A * Returns a string representation of this drop location.
0N/A * This method is intended to be used for debugging purposes,
0N/A * and the content and format of the returned string may vary
0N/A * between implementations.
0N/A *
0N/A * @return a string representation of this drop location
0N/A */
0N/A public String toString() {
0N/A return getClass().getName()
0N/A + "[dropPoint=" + getDropPoint() + ","
0N/A + "index=" + index + ","
0N/A + "bias=" + bias + "]";
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * TransferHandler used if one hasn't been supplied by the UI.
0N/A */
0N/A private static DefaultTransferHandler defaultTransferHandler;
0N/A
0N/A /**
0N/A * Maps from class name to Boolean indicating if
0N/A * <code>processInputMethodEvent</code> has been overriden.
0N/A */
611N/A private static Map<String, Boolean> overrideMap;
0N/A
0N/A /**
0N/A * Returns a string representation of this <code>JTextComponent</code>.
0N/A * This method is intended to be used only for debugging purposes, and the
0N/A * content and format of the returned string may vary between
0N/A * implementations. The returned string may be empty but may not
0N/A * be <code>null</code>.
0N/A * <P>
0N/A * Overriding <code>paramString</code> to provide information about the
0N/A * specific new aspects of the JFC components.
0N/A *
0N/A * @return a string representation of this <code>JTextComponent</code>
0N/A */
0N/A protected String paramString() {
0N/A String editableString = (editable ?
0N/A "true" : "false");
0N/A String caretColorString = (caretColor != null ?
0N/A caretColor.toString() : "");
0N/A String selectionColorString = (selectionColor != null ?
0N/A selectionColor.toString() : "");
0N/A String selectedTextColorString = (selectedTextColor != null ?
0N/A selectedTextColor.toString() : "");
0N/A String disabledTextColorString = (disabledTextColor != null ?
0N/A disabledTextColor.toString() : "");
0N/A String marginString = (margin != null ?
0N/A margin.toString() : "");
0N/A
0N/A return super.paramString() +
0N/A ",caretColor=" + caretColorString +
0N/A ",disabledTextColor=" + disabledTextColorString +
0N/A ",editable=" + editableString +
0N/A ",margin=" + marginString +
0N/A ",selectedTextColor=" + selectedTextColorString +
0N/A ",selectionColor=" + selectionColorString;
0N/A }
0N/A
0N/A
0N/A /**
0N/A * A Simple TransferHandler that exports the data as a String, and
0N/A * imports the data from the String clipboard. This is only used
0N/A * if the UI hasn't supplied one, which would only happen if someone
0N/A * hasn't subclassed Basic.
0N/A */
0N/A static class DefaultTransferHandler extends TransferHandler implements
0N/A UIResource {
0N/A public void exportToClipboard(JComponent comp, Clipboard clipboard,
0N/A int action) throws IllegalStateException {
0N/A if (comp instanceof JTextComponent) {
0N/A JTextComponent text = (JTextComponent)comp;
0N/A int p0 = text.getSelectionStart();
0N/A int p1 = text.getSelectionEnd();
0N/A if (p0 != p1) {
0N/A try {
0N/A Document doc = text.getDocument();
0N/A String srcData = doc.getText(p0, p1 - p0);
0N/A StringSelection contents =new StringSelection(srcData);
0N/A
0N/A // this may throw an IllegalStateException,
0N/A // but it will be caught and handled in the
0N/A // action that invoked this method
0N/A clipboard.setContents(contents, null);
0N/A
0N/A if (action == TransferHandler.MOVE) {
0N/A doc.remove(p0, p1 - p0);
0N/A }
0N/A } catch (BadLocationException ble) {}
0N/A }
0N/A }
0N/A }
0N/A public boolean importData(JComponent comp, Transferable t) {
0N/A if (comp instanceof JTextComponent) {
0N/A DataFlavor flavor = getFlavor(t.getTransferDataFlavors());
0N/A
0N/A if (flavor != null) {
0N/A InputContext ic = comp.getInputContext();
0N/A if (ic != null) {
0N/A ic.endComposition();
0N/A }
0N/A try {
0N/A String data = (String)t.getTransferData(flavor);
0N/A
0N/A ((JTextComponent)comp).replaceSelection(data);
0N/A return true;
0N/A } catch (UnsupportedFlavorException ufe) {
0N/A } catch (IOException ioe) {
0N/A }
0N/A }
0N/A }
0N/A return false;
0N/A }
0N/A public boolean canImport(JComponent comp,
0N/A DataFlavor[] transferFlavors) {
0N/A JTextComponent c = (JTextComponent)comp;
0N/A if (!(c.isEditable() && c.isEnabled())) {
0N/A return false;
0N/A }
0N/A return (getFlavor(transferFlavors) != null);
0N/A }
0N/A public int getSourceActions(JComponent c) {
0N/A return NONE;
0N/A }
0N/A private DataFlavor getFlavor(DataFlavor[] flavors) {
0N/A if (flavors != null) {
611N/A for (DataFlavor flavor : flavors) {
611N/A if (flavor.equals(DataFlavor.stringFlavor)) {
611N/A return flavor;
0N/A }
0N/A }
0N/A }
0N/A return null;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns the JTextComponent that most recently had focus. The returned
0N/A * value may currently have focus.
0N/A */
0N/A static final JTextComponent getFocusedComponent() {
0N/A return (JTextComponent)AppContext.getAppContext().
0N/A get(FOCUSED_COMPONENT);
0N/A }
0N/A
0N/A private int getCurrentEventModifiers() {
0N/A int modifiers = 0;
0N/A AWTEvent currentEvent = EventQueue.getCurrentEvent();
0N/A if (currentEvent instanceof InputEvent) {
0N/A modifiers = ((InputEvent)currentEvent).getModifiers();
0N/A } else if (currentEvent instanceof ActionEvent) {
0N/A modifiers = ((ActionEvent)currentEvent).getModifiers();
0N/A }
0N/A return modifiers;
0N/A }
0N/A
0N/A private static final Object KEYMAP_TABLE =
0N/A new StringBuilder("JTextComponent_KeymapTable");
2973N/A
0N/A //
0N/A // member variables used for on-the-spot input method
0N/A // editing style support
0N/A //
0N/A private transient InputMethodRequests inputMethodRequestsHandler;
0N/A private SimpleAttributeSet composedTextAttribute;
0N/A private String composedTextContent;
0N/A private Position composedTextStart;
0N/A private Position composedTextEnd;
0N/A private Position latestCommittedTextStart;
0N/A private Position latestCommittedTextEnd;
0N/A private ComposedTextCaret composedTextCaret;
0N/A private transient Caret originalCaret;
0N/A /**
0N/A * Set to true after the check for the override of processInputMethodEvent
0N/A * has been checked.
0N/A */
0N/A private boolean checkedInputOverride;
0N/A private boolean needToSendKeyTypedEvent;
0N/A
0N/A static class DefaultKeymap implements Keymap {
0N/A
0N/A DefaultKeymap(String nm, Keymap parent) {
0N/A this.nm = nm;
0N/A this.parent = parent;
611N/A bindings = new Hashtable<KeyStroke, Action>();
0N/A }
0N/A
0N/A /**
0N/A * Fetch the default action to fire if a
0N/A * key is typed (ie a KEY_TYPED KeyEvent is received)
0N/A * and there is no binding for it. Typically this
0N/A * would be some action that inserts text so that
0N/A * the keymap doesn't require an action for each
0N/A * possible key.
0N/A */
0N/A public Action getDefaultAction() {
0N/A if (defaultAction != null) {
0N/A return defaultAction;
0N/A }
0N/A return (parent != null) ? parent.getDefaultAction() : null;
0N/A }
0N/A
0N/A /**
0N/A * Set the default action to fire if a key is typed.
0N/A */
0N/A public void setDefaultAction(Action a) {
0N/A defaultAction = a;
0N/A }
0N/A
0N/A public String getName() {
0N/A return nm;
0N/A }
0N/A
0N/A public Action getAction(KeyStroke key) {
611N/A Action a = bindings.get(key);
0N/A if ((a == null) && (parent != null)) {
0N/A a = parent.getAction(key);
0N/A }
0N/A return a;
0N/A }
0N/A
0N/A public KeyStroke[] getBoundKeyStrokes() {
0N/A KeyStroke[] keys = new KeyStroke[bindings.size()];
0N/A int i = 0;
611N/A for (Enumeration<KeyStroke> e = bindings.keys() ; e.hasMoreElements() ;) {
611N/A keys[i++] = e.nextElement();
0N/A }
0N/A return keys;
0N/A }
0N/A
0N/A public Action[] getBoundActions() {
0N/A Action[] actions = new Action[bindings.size()];
0N/A int i = 0;
611N/A for (Enumeration<Action> e = bindings.elements() ; e.hasMoreElements() ;) {
611N/A actions[i++] = e.nextElement();
0N/A }
0N/A return actions;
0N/A }
0N/A
0N/A public KeyStroke[] getKeyStrokesForAction(Action a) {
0N/A if (a == null) {
0N/A return null;
0N/A }
0N/A KeyStroke[] retValue = null;
0N/A // Determine local bindings first.
611N/A Vector<KeyStroke> keyStrokes = null;
611N/A for (Enumeration<KeyStroke> keys = bindings.keys(); keys.hasMoreElements();) {
611N/A KeyStroke key = keys.nextElement();
0N/A if (bindings.get(key) == a) {
0N/A if (keyStrokes == null) {
611N/A keyStrokes = new Vector<KeyStroke>();
0N/A }
0N/A keyStrokes.addElement(key);
0N/A }
0N/A }
0N/A // See if the parent has any.
0N/A if (parent != null) {
0N/A KeyStroke[] pStrokes = parent.getKeyStrokesForAction(a);
0N/A if (pStrokes != null) {
0N/A // Remove any bindings defined in the parent that
0N/A // are locally defined.
0N/A int rCount = 0;
0N/A for (int counter = pStrokes.length - 1; counter >= 0;
0N/A counter--) {
0N/A if (isLocallyDefined(pStrokes[counter])) {
0N/A pStrokes[counter] = null;
0N/A rCount++;
0N/A }
0N/A }
0N/A if (rCount > 0 && rCount < pStrokes.length) {
0N/A if (keyStrokes == null) {
611N/A keyStrokes = new Vector<KeyStroke>();
0N/A }
0N/A for (int counter = pStrokes.length - 1; counter >= 0;
0N/A counter--) {
0N/A if (pStrokes[counter] != null) {
0N/A keyStrokes.addElement(pStrokes[counter]);
0N/A }
0N/A }
0N/A }
0N/A else if (rCount == 0) {
0N/A if (keyStrokes == null) {
0N/A retValue = pStrokes;
0N/A }
0N/A else {
0N/A retValue = new KeyStroke[keyStrokes.size() +
0N/A pStrokes.length];
0N/A keyStrokes.copyInto(retValue);
0N/A System.arraycopy(pStrokes, 0, retValue,
0N/A keyStrokes.size(), pStrokes.length);
0N/A keyStrokes = null;
0N/A }
0N/A }
0N/A }
0N/A }
0N/A if (keyStrokes != null) {
0N/A retValue = new KeyStroke[keyStrokes.size()];
0N/A keyStrokes.copyInto(retValue);
0N/A }
0N/A return retValue;
0N/A }
0N/A
0N/A public boolean isLocallyDefined(KeyStroke key) {
0N/A return bindings.containsKey(key);
0N/A }
0N/A
0N/A public void addActionForKeyStroke(KeyStroke key, Action a) {
0N/A bindings.put(key, a);
0N/A }
0N/A
0N/A public void removeKeyStrokeBinding(KeyStroke key) {
0N/A bindings.remove(key);
0N/A }
0N/A
0N/A public void removeBindings() {
0N/A bindings.clear();
0N/A }
0N/A
0N/A public Keymap getResolveParent() {
0N/A return parent;
0N/A }
0N/A
0N/A public void setResolveParent(Keymap parent) {
0N/A this.parent = parent;
0N/A }
0N/A
0N/A /**
0N/A * String representation of the keymap... potentially
0N/A * a very long string.
0N/A */
0N/A public String toString() {
0N/A return "Keymap[" + nm + "]" + bindings;
0N/A }
0N/A
0N/A String nm;
0N/A Keymap parent;
611N/A Hashtable<KeyStroke, Action> bindings;
0N/A Action defaultAction;
0N/A }
0N/A
0N/A
0N/A /**
0N/A * KeymapWrapper wraps a Keymap inside an InputMap. For KeymapWrapper
0N/A * to be useful it must be used with a KeymapActionMap.
0N/A * KeymapWrapper for the most part, is an InputMap with two parents.
0N/A * The first parent visited is ALWAYS the Keymap, with the second
0N/A * parent being the parent inherited from InputMap. If
0N/A * <code>keymap.getAction</code> returns null, implying the Keymap
0N/A * does not have a binding for the KeyStroke,
0N/A * the parent is then visited. If the Keymap has a binding, the
0N/A * Action is returned, if not and the KeyStroke represents a
0N/A * KeyTyped event and the Keymap has a defaultAction,
0N/A * <code>DefaultActionKey</code> is returned.
0N/A * <p>KeymapActionMap is then able to transate the object passed in
0N/A * to either message the Keymap, or message its default implementation.
0N/A */
0N/A static class KeymapWrapper extends InputMap {
0N/A static final Object DefaultActionKey = new Object();
0N/A
0N/A private Keymap keymap;
0N/A
0N/A KeymapWrapper(Keymap keymap) {
0N/A this.keymap = keymap;
0N/A }
0N/A
0N/A public KeyStroke[] keys() {
0N/A KeyStroke[] sKeys = super.keys();
0N/A KeyStroke[] keymapKeys = keymap.getBoundKeyStrokes();
0N/A int sCount = (sKeys == null) ? 0 : sKeys.length;
0N/A int keymapCount = (keymapKeys == null) ? 0 : keymapKeys.length;
0N/A if (sCount == 0) {
0N/A return keymapKeys;
0N/A }
0N/A if (keymapCount == 0) {
0N/A return sKeys;
0N/A }
0N/A KeyStroke[] retValue = new KeyStroke[sCount + keymapCount];
0N/A // There may be some duplication here...
0N/A System.arraycopy(sKeys, 0, retValue, 0, sCount);
0N/A System.arraycopy(keymapKeys, 0, retValue, sCount, keymapCount);
0N/A return retValue;
0N/A }
0N/A
0N/A public int size() {
0N/A // There may be some duplication here...
0N/A KeyStroke[] keymapStrokes = keymap.getBoundKeyStrokes();
0N/A int keymapCount = (keymapStrokes == null) ? 0:
0N/A keymapStrokes.length;
0N/A return super.size() + keymapCount;
0N/A }
0N/A
0N/A public Object get(KeyStroke keyStroke) {
0N/A Object retValue = keymap.getAction(keyStroke);
0N/A if (retValue == null) {
0N/A retValue = super.get(keyStroke);
0N/A if (retValue == null &&
0N/A keyStroke.getKeyChar() != KeyEvent.CHAR_UNDEFINED &&
0N/A keymap.getDefaultAction() != null) {
0N/A // Implies this is a KeyTyped event, use the default
0N/A // action.
0N/A retValue = DefaultActionKey;
0N/A }
0N/A }
0N/A return retValue;
0N/A }
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Wraps a Keymap inside an ActionMap. This is used with
0N/A * a KeymapWrapper. If <code>get</code> is passed in
0N/A * <code>KeymapWrapper.DefaultActionKey</code>, the default action is
0N/A * returned, otherwise if the key is an Action, it is returned.
0N/A */
0N/A static class KeymapActionMap extends ActionMap {
0N/A private Keymap keymap;
0N/A
0N/A KeymapActionMap(Keymap keymap) {
0N/A this.keymap = keymap;
0N/A }
0N/A
0N/A public Object[] keys() {
0N/A Object[] sKeys = super.keys();
0N/A Object[] keymapKeys = keymap.getBoundActions();
0N/A int sCount = (sKeys == null) ? 0 : sKeys.length;
0N/A int keymapCount = (keymapKeys == null) ? 0 : keymapKeys.length;
0N/A boolean hasDefault = (keymap.getDefaultAction() != null);
0N/A if (hasDefault) {
0N/A keymapCount++;
0N/A }
0N/A if (sCount == 0) {
0N/A if (hasDefault) {
0N/A Object[] retValue = new Object[keymapCount];
0N/A if (keymapCount > 1) {
0N/A System.arraycopy(keymapKeys, 0, retValue, 0,
0N/A keymapCount - 1);
0N/A }
0N/A retValue[keymapCount - 1] = KeymapWrapper.DefaultActionKey;
0N/A return retValue;
0N/A }
0N/A return keymapKeys;
0N/A }
0N/A if (keymapCount == 0) {
0N/A return sKeys;
0N/A }
0N/A Object[] retValue = new Object[sCount + keymapCount];
0N/A // There may be some duplication here...
0N/A System.arraycopy(sKeys, 0, retValue, 0, sCount);
0N/A if (hasDefault) {
0N/A if (keymapCount > 1) {
0N/A System.arraycopy(keymapKeys, 0, retValue, sCount,
0N/A keymapCount - 1);
0N/A }
0N/A retValue[sCount + keymapCount - 1] = KeymapWrapper.
0N/A DefaultActionKey;
0N/A }
0N/A else {
0N/A System.arraycopy(keymapKeys, 0, retValue, sCount, keymapCount);
0N/A }
0N/A return retValue;
0N/A }
0N/A
0N/A public int size() {
0N/A // There may be some duplication here...
0N/A Object[] actions = keymap.getBoundActions();
0N/A int keymapCount = (actions == null) ? 0 : actions.length;
0N/A if (keymap.getDefaultAction() != null) {
0N/A keymapCount++;
0N/A }
0N/A return super.size() + keymapCount;
0N/A }
0N/A
0N/A public Action get(Object key) {
0N/A Action retValue = super.get(key);
0N/A if (retValue == null) {
0N/A // Try the Keymap.
0N/A if (key == KeymapWrapper.DefaultActionKey) {
0N/A retValue = keymap.getDefaultAction();
0N/A }
0N/A else if (key instanceof Action) {
0N/A // This is a little iffy, technically an Action is
0N/A // a valid Key. We're assuming the Action came from
0N/A // the InputMap though.
0N/A retValue = (Action)key;
0N/A }
0N/A }
0N/A return retValue;
0N/A }
0N/A }
0N/A
0N/A private static final Object FOCUSED_COMPONENT =
0N/A new StringBuilder("JTextComponent_FocusedComponent");
0N/A
0N/A /**
0N/A * The default keymap that will be shared by all
0N/A * <code>JTextComponent</code> instances unless they
0N/A * have had a different keymap set.
0N/A */
0N/A public static final String DEFAULT_KEYMAP = "default";
0N/A
0N/A /**
0N/A * Event to use when firing a notification of change to caret
0N/A * position. This is mutable so that the event can be reused
0N/A * since caret events can be fairly high in bandwidth.
0N/A */
0N/A static class MutableCaretEvent extends CaretEvent implements ChangeListener, FocusListener, MouseListener {
0N/A
0N/A MutableCaretEvent(JTextComponent c) {
0N/A super(c);
0N/A }
0N/A
0N/A final void fire() {
0N/A JTextComponent c = (JTextComponent) getSource();
0N/A if (c != null) {
0N/A Caret caret = c.getCaret();
0N/A dot = caret.getDot();
0N/A mark = caret.getMark();
0N/A c.fireCaretUpdate(this);
0N/A }
0N/A }
0N/A
0N/A public final String toString() {
0N/A return "dot=" + dot + "," + "mark=" + mark;
0N/A }
0N/A
0N/A // --- CaretEvent methods -----------------------
0N/A
0N/A public final int getDot() {
0N/A return dot;
0N/A }
0N/A
0N/A public final int getMark() {
0N/A return mark;
0N/A }
0N/A
0N/A // --- ChangeListener methods -------------------
0N/A
0N/A public final void stateChanged(ChangeEvent e) {
0N/A if (! dragActive) {
0N/A fire();
0N/A }
0N/A }
0N/A
0N/A // --- FocusListener methods -----------------------------------
0N/A public void focusGained(FocusEvent fe) {
0N/A AppContext.getAppContext().put(FOCUSED_COMPONENT,
0N/A fe.getSource());
0N/A }
0N/A
0N/A public void focusLost(FocusEvent fe) {
0N/A }
0N/A
0N/A // --- MouseListener methods -----------------------------------
0N/A
0N/A /**
0N/A * Requests focus on the associated
0N/A * text component, and try to set the cursor position.
0N/A *
0N/A * @param e the mouse event
0N/A * @see MouseListener#mousePressed
0N/A */
0N/A public final void mousePressed(MouseEvent e) {
0N/A dragActive = true;
0N/A }
0N/A
0N/A /**
0N/A * Called when the mouse is released.
0N/A *
0N/A * @param e the mouse event
0N/A * @see MouseListener#mouseReleased
0N/A */
0N/A public final void mouseReleased(MouseEvent e) {
0N/A dragActive = false;
0N/A fire();
0N/A }
0N/A
0N/A public final void mouseClicked(MouseEvent e) {
0N/A }
0N/A
0N/A public final void mouseEntered(MouseEvent e) {
0N/A }
0N/A
0N/A public final void mouseExited(MouseEvent e) {
0N/A }
0N/A
0N/A private boolean dragActive;
0N/A private int dot;
0N/A private int mark;
0N/A }
0N/A
0N/A //
0N/A // Process any input method events that the component itself
0N/A // recognizes. The default on-the-spot handling for input method
0N/A // composed(uncommitted) text is done here after all input
0N/A // method listeners get called for stealing the events.
0N/A //
0N/A protected void processInputMethodEvent(InputMethodEvent e) {
0N/A // let listeners handle the events
0N/A super.processInputMethodEvent(e);
0N/A
0N/A if (!e.isConsumed()) {
0N/A if (! isEditable()) {
0N/A return;
0N/A } else {
0N/A switch (e.getID()) {
0N/A case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED:
0N/A replaceInputMethodText(e);
0N/A
0N/A // fall through
0N/A
0N/A case InputMethodEvent.CARET_POSITION_CHANGED:
0N/A setInputMethodCaretPosition(e);
0N/A break;
0N/A }
0N/A }
0N/A
0N/A e.consume();
0N/A }
0N/A }
0N/A
0N/A //
0N/A // Overrides this method to become an active input method client.
0N/A //
0N/A public InputMethodRequests getInputMethodRequests() {
0N/A if (inputMethodRequestsHandler == null) {
611N/A inputMethodRequestsHandler = new InputMethodRequestsHandler();
0N/A Document doc = getDocument();
0N/A if (doc != null) {
0N/A doc.addDocumentListener((DocumentListener)inputMethodRequestsHandler);
0N/A }
0N/A }
0N/A
0N/A return inputMethodRequestsHandler;
0N/A }
0N/A
0N/A //
0N/A // Overrides this method to watch the listener installed.
0N/A //
0N/A public void addInputMethodListener(InputMethodListener l) {
0N/A super.addInputMethodListener(l);
0N/A if (l != null) {
0N/A needToSendKeyTypedEvent = false;
0N/A checkedInputOverride = true;
0N/A }
0N/A }
0N/A
0N/A
0N/A //
0N/A // Default implementation of the InputMethodRequests interface.
0N/A //
0N/A class InputMethodRequestsHandler implements InputMethodRequests, DocumentListener {
0N/A
0N/A // --- InputMethodRequests methods ---
0N/A
0N/A public AttributedCharacterIterator cancelLatestCommittedText(
0N/A Attribute[] attributes) {
0N/A Document doc = getDocument();
0N/A if ((doc != null) && (latestCommittedTextStart != null)
0N/A && (!latestCommittedTextStart.equals(latestCommittedTextEnd))) {
0N/A try {
0N/A int startIndex = latestCommittedTextStart.getOffset();
0N/A int endIndex = latestCommittedTextEnd.getOffset();
0N/A String latestCommittedText =
0N/A doc.getText(startIndex, endIndex - startIndex);
0N/A doc.remove(startIndex, endIndex - startIndex);
0N/A return new AttributedString(latestCommittedText).getIterator();
0N/A } catch (BadLocationException ble) {}
0N/A }
0N/A return null;
0N/A }
0N/A
0N/A public AttributedCharacterIterator getCommittedText(int beginIndex,
0N/A int endIndex, Attribute[] attributes) {
0N/A int composedStartIndex = 0;
0N/A int composedEndIndex = 0;
0N/A if (composedTextExists()) {
0N/A composedStartIndex = composedTextStart.getOffset();
0N/A composedEndIndex = composedTextEnd.getOffset();
0N/A }
0N/A
0N/A String committed;
0N/A try {
0N/A if (beginIndex < composedStartIndex) {
0N/A if (endIndex <= composedStartIndex) {
0N/A committed = getText(beginIndex, endIndex - beginIndex);
0N/A } else {
0N/A int firstPartLength = composedStartIndex - beginIndex;
0N/A committed = getText(beginIndex, firstPartLength) +
0N/A getText(composedEndIndex, endIndex - beginIndex - firstPartLength);
0N/A }
0N/A } else {
0N/A committed = getText(beginIndex + (composedEndIndex - composedStartIndex),
0N/A endIndex - beginIndex);
0N/A }
0N/A } catch (BadLocationException ble) {
0N/A throw new IllegalArgumentException("Invalid range");
0N/A }
0N/A return new AttributedString(committed).getIterator();
0N/A }
0N/A
0N/A public int getCommittedTextLength() {
0N/A Document doc = getDocument();
0N/A int length = 0;
0N/A if (doc != null) {
0N/A length = doc.getLength();
0N/A if (composedTextContent != null) {
0N/A if (composedTextEnd == null
0N/A || composedTextStart == null) {
0N/A /*
0N/A * fix for : 6355666
0N/A * this is the case when this method is invoked
0N/A * from DocumentListener. At this point
0N/A * composedTextEnd and composedTextStart are
0N/A * not defined yet.
0N/A */
0N/A length -= composedTextContent.length();
0N/A } else {
0N/A length -= composedTextEnd.getOffset() -
0N/A composedTextStart.getOffset();
0N/A }
0N/A }
0N/A }
0N/A return length;
0N/A }
0N/A
0N/A public int getInsertPositionOffset() {
0N/A int composedStartIndex = 0;
0N/A int composedEndIndex = 0;
0N/A if (composedTextExists()) {
0N/A composedStartIndex = composedTextStart.getOffset();
0N/A composedEndIndex = composedTextEnd.getOffset();
0N/A }
0N/A int caretIndex = getCaretPosition();
0N/A
0N/A if (caretIndex < composedStartIndex) {
0N/A return caretIndex;
0N/A } else if (caretIndex < composedEndIndex) {
0N/A return composedStartIndex;
0N/A } else {
0N/A return caretIndex - (composedEndIndex - composedStartIndex);
0N/A }
0N/A }
0N/A
0N/A public TextHitInfo getLocationOffset(int x, int y) {
0N/A if (composedTextAttribute == null) {
0N/A return null;
0N/A } else {
0N/A Point p = getLocationOnScreen();
0N/A p.x = x - p.x;
0N/A p.y = y - p.y;
0N/A int pos = viewToModel(p);
0N/A if ((pos >= composedTextStart.getOffset()) &&
0N/A (pos <= composedTextEnd.getOffset())) {
0N/A return TextHitInfo.leading(pos - composedTextStart.getOffset());
0N/A } else {
0N/A return null;
0N/A }
0N/A }
0N/A }
0N/A
0N/A public Rectangle getTextLocation(TextHitInfo offset) {
0N/A Rectangle r;
0N/A
0N/A try {
0N/A r = modelToView(getCaretPosition());
0N/A if (r != null) {
0N/A Point p = getLocationOnScreen();
0N/A r.translate(p.x, p.y);
0N/A }
0N/A } catch (BadLocationException ble) {
0N/A r = null;
0N/A }
0N/A
0N/A if (r == null)
0N/A r = new Rectangle();
0N/A
0N/A return r;
0N/A }
0N/A
0N/A public AttributedCharacterIterator getSelectedText(
0N/A Attribute[] attributes) {
0N/A String selection = JTextComponent.this.getSelectedText();
0N/A if (selection != null) {
0N/A return new AttributedString(selection).getIterator();
0N/A } else {
0N/A return null;
0N/A }
0N/A }
0N/A
0N/A // --- DocumentListener methods ---
0N/A
0N/A public void changedUpdate(DocumentEvent e) {
0N/A latestCommittedTextStart = latestCommittedTextEnd = null;
0N/A }
0N/A
0N/A public void insertUpdate(DocumentEvent e) {
0N/A latestCommittedTextStart = latestCommittedTextEnd = null;
0N/A }
0N/A
0N/A public void removeUpdate(DocumentEvent e) {
0N/A latestCommittedTextStart = latestCommittedTextEnd = null;
0N/A }
0N/A }
0N/A
0N/A //
0N/A // Replaces the current input method (composed) text according to
0N/A // the passed input method event. This method also inserts the
0N/A // committed text into the document.
0N/A //
0N/A private void replaceInputMethodText(InputMethodEvent e) {
0N/A int commitCount = e.getCommittedCharacterCount();
0N/A AttributedCharacterIterator text = e.getText();
0N/A int composedTextIndex;
0N/A
0N/A // old composed text deletion
0N/A Document doc = getDocument();
0N/A if (composedTextExists()) {
0N/A try {
0N/A doc.remove(composedTextStart.getOffset(),
0N/A composedTextEnd.getOffset() -
0N/A composedTextStart.getOffset());
0N/A } catch (BadLocationException ble) {}
0N/A composedTextStart = composedTextEnd = null;
0N/A composedTextAttribute = null;
0N/A composedTextContent = null;
0N/A }
0N/A
0N/A if (text != null) {
0N/A text.first();
0N/A int committedTextStartIndex = 0;
0N/A int committedTextEndIndex = 0;
0N/A
0N/A // committed text insertion
0N/A if (commitCount > 0) {
0N/A // Remember latest committed text start index
0N/A committedTextStartIndex = caret.getDot();
0N/A
0N/A // Need to generate KeyTyped events for the committed text for components
0N/A // that are not aware they are active input method clients.
0N/A if (shouldSynthensizeKeyEvents()) {
0N/A for (char c = text.current(); commitCount > 0;
0N/A c = text.next(), commitCount--) {
0N/A KeyEvent ke = new KeyEvent(this, KeyEvent.KEY_TYPED,
0N/A EventQueue.getMostRecentEventTime(),
0N/A 0, KeyEvent.VK_UNDEFINED, c);
0N/A processKeyEvent(ke);
0N/A }
0N/A } else {
2973N/A StringBuilder strBuf = new StringBuilder();
0N/A for (char c = text.current(); commitCount > 0;
0N/A c = text.next(), commitCount--) {
0N/A strBuf.append(c);
0N/A }
0N/A
0N/A // map it to an ActionEvent
2973N/A mapCommittedTextToAction(strBuf.toString());
0N/A }
0N/A
0N/A // Remember latest committed text end index
0N/A committedTextEndIndex = caret.getDot();
0N/A }
0N/A
0N/A // new composed text insertion
0N/A composedTextIndex = text.getIndex();
0N/A if (composedTextIndex < text.getEndIndex()) {
0N/A createComposedTextAttribute(composedTextIndex, text);
0N/A try {
0N/A replaceSelection(null);
0N/A doc.insertString(caret.getDot(), composedTextContent,
0N/A composedTextAttribute);
0N/A composedTextStart = doc.createPosition(caret.getDot() -
0N/A composedTextContent.length());
0N/A composedTextEnd = doc.createPosition(caret.getDot());
0N/A } catch (BadLocationException ble) {
0N/A composedTextStart = composedTextEnd = null;
0N/A composedTextAttribute = null;
0N/A composedTextContent = null;
0N/A }
0N/A }
0N/A
0N/A // Save the latest committed text information
0N/A if (committedTextStartIndex != committedTextEndIndex) {
0N/A try {
0N/A latestCommittedTextStart = doc.
0N/A createPosition(committedTextStartIndex);
0N/A latestCommittedTextEnd = doc.
0N/A createPosition(committedTextEndIndex);
0N/A } catch (BadLocationException ble) {
0N/A latestCommittedTextStart =
0N/A latestCommittedTextEnd = null;
0N/A }
0N/A } else {
0N/A latestCommittedTextStart =
0N/A latestCommittedTextEnd = null;
0N/A }
0N/A }
0N/A }
0N/A
0N/A private void createComposedTextAttribute(int composedIndex,
0N/A AttributedCharacterIterator text) {
0N/A Document doc = getDocument();
2973N/A StringBuilder strBuf = new StringBuilder();
0N/A
0N/A // create attributed string with no attributes
0N/A for (char c = text.setIndex(composedIndex);
0N/A c != CharacterIterator.DONE; c = text.next()) {
0N/A strBuf.append(c);
0N/A }
0N/A
2973N/A composedTextContent = strBuf.toString();
0N/A composedTextAttribute = new SimpleAttributeSet();
0N/A composedTextAttribute.addAttribute(StyleConstants.ComposedTextAttribute,
0N/A new AttributedString(text, composedIndex, text.getEndIndex()));
0N/A }
0N/A
1638N/A /**
1638N/A * Saves composed text around the specified position.
1638N/A *
1638N/A * The composed text (if any) around the specified position is saved
1638N/A * in a backing store and removed from the document.
1638N/A *
1638N/A * @param pos document position to identify the composed text location
1638N/A * @return {@code true} if the composed text exists and is saved,
1638N/A * {@code false} otherwise
1638N/A * @see #restoreComposedText
3452N/A * @since 1.7
1638N/A */
1638N/A protected boolean saveComposedText(int pos) {
0N/A if (composedTextExists()) {
0N/A int start = composedTextStart.getOffset();
0N/A int len = composedTextEnd.getOffset() -
0N/A composedTextStart.getOffset();
0N/A if (pos >= start && pos <= start + len) {
0N/A try {
0N/A getDocument().remove(start, len);
0N/A return true;
0N/A } catch (BadLocationException ble) {}
0N/A }
0N/A }
0N/A return false;
0N/A }
0N/A
1638N/A /**
1638N/A * Restores composed text previously saved by {@code saveComposedText}.
1638N/A *
1638N/A * The saved composed text is inserted back into the document. This method
1638N/A * should be invoked only if {@code saveComposedText} returns {@code true}.
1638N/A *
1638N/A * @see #saveComposedText
3452N/A * @since 1.7
1638N/A */
1638N/A protected void restoreComposedText() {
0N/A Document doc = getDocument();
0N/A try {
0N/A doc.insertString(caret.getDot(),
0N/A composedTextContent,
0N/A composedTextAttribute);
0N/A composedTextStart = doc.createPosition(caret.getDot() -
0N/A composedTextContent.length());
0N/A composedTextEnd = doc.createPosition(caret.getDot());
0N/A } catch (BadLocationException ble) {}
0N/A }
0N/A
0N/A //
0N/A // Map committed text to an ActionEvent. If the committed text length is 1,
0N/A // treat it as a KeyStroke, otherwise or there is no KeyStroke defined,
0N/A // treat it just as a default action.
0N/A //
0N/A private void mapCommittedTextToAction(String committedText) {
0N/A Keymap binding = getKeymap();
0N/A if (binding != null) {
0N/A Action a = null;
0N/A if (committedText.length() == 1) {
0N/A KeyStroke k = KeyStroke.getKeyStroke(committedText.charAt(0));
0N/A a = binding.getAction(k);
0N/A }
0N/A
0N/A if (a == null) {
0N/A a = binding.getDefaultAction();
0N/A }
0N/A
0N/A if (a != null) {
0N/A ActionEvent ae =
0N/A new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
0N/A committedText,
0N/A EventQueue.getMostRecentEventTime(),
0N/A getCurrentEventModifiers());
0N/A a.actionPerformed(ae);
0N/A }
0N/A }
0N/A }
0N/A
0N/A //
0N/A // Sets the caret position according to the passed input method
0N/A // event. Also, sets/resets composed text caret appropriately.
0N/A //
0N/A private void setInputMethodCaretPosition(InputMethodEvent e) {
0N/A int dot;
0N/A
0N/A if (composedTextExists()) {
0N/A dot = composedTextStart.getOffset();
0N/A if (!(caret instanceof ComposedTextCaret)) {
0N/A if (composedTextCaret == null) {
0N/A composedTextCaret = new ComposedTextCaret();
0N/A }
0N/A originalCaret = caret;
0N/A // Sets composed text caret
0N/A exchangeCaret(originalCaret, composedTextCaret);
0N/A }
0N/A
0N/A TextHitInfo caretPos = e.getCaret();
0N/A if (caretPos != null) {
0N/A int index = caretPos.getInsertionIndex();
0N/A dot += index;
0N/A if (index == 0) {
0N/A // Scroll the component if needed so that the composed text
0N/A // becomes visible.
0N/A try {
0N/A Rectangle d = modelToView(dot);
0N/A Rectangle end = modelToView(composedTextEnd.getOffset());
0N/A Rectangle b = getBounds();
0N/A d.x += Math.min(end.x - d.x, b.width);
0N/A scrollRectToVisible(d);
0N/A } catch (BadLocationException ble) {}
0N/A }
0N/A }
0N/A caret.setDot(dot);
0N/A } else if (caret instanceof ComposedTextCaret) {
0N/A dot = caret.getDot();
0N/A // Restores original caret
0N/A exchangeCaret(caret, originalCaret);
0N/A caret.setDot(dot);
0N/A }
0N/A }
0N/A
0N/A private void exchangeCaret(Caret oldCaret, Caret newCaret) {
0N/A int blinkRate = oldCaret.getBlinkRate();
0N/A setCaret(newCaret);
0N/A caret.setBlinkRate(blinkRate);
0N/A caret.setVisible(hasFocus());
0N/A }
0N/A
0N/A /**
0N/A * Returns true if KeyEvents should be synthesized from an InputEvent.
0N/A */
0N/A private boolean shouldSynthensizeKeyEvents() {
0N/A if (!checkedInputOverride) {
0N/A checkedInputOverride = true;
0N/A needToSendKeyTypedEvent =
0N/A !isProcessInputMethodEventOverridden();
0N/A }
0N/A return needToSendKeyTypedEvent;
0N/A }
0N/A
0N/A //
0N/A // Checks whether the client code overrides processInputMethodEvent. If it is overridden,
0N/A // need not to generate KeyTyped events for committed text. If it's not, behave as an
0N/A // passive input method client.
0N/A //
0N/A private boolean isProcessInputMethodEventOverridden() {
0N/A if (overrideMap == null) {
611N/A overrideMap = Collections.synchronizedMap(new HashMap<String, Boolean>());
0N/A }
611N/A Boolean retValue = overrideMap.get(getClass().getName());
0N/A
0N/A if (retValue != null) {
0N/A return retValue.booleanValue();
0N/A }
611N/A Boolean ret = AccessController.doPrivileged(new
611N/A PrivilegedAction<Boolean>() {
611N/A public Boolean run() {
0N/A return isProcessInputMethodEventOverridden(
0N/A JTextComponent.this.getClass());
0N/A }
0N/A });
0N/A
0N/A return ret.booleanValue();
0N/A }
0N/A
0N/A //
0N/A // Checks whether a composed text in this text component
0N/A //
0N/A boolean composedTextExists() {
0N/A return (composedTextStart != null);
0N/A }
0N/A
0N/A //
0N/A // Caret implementation for editing the composed text.
0N/A //
0N/A class ComposedTextCaret extends DefaultCaret implements Serializable {
0N/A Color bg;
0N/A
0N/A //
0N/A // Get the background color of the component
0N/A //
0N/A public void install(JTextComponent c) {
0N/A super.install(c);
0N/A
0N/A Document doc = c.getDocument();
0N/A if (doc instanceof StyledDocument) {
0N/A StyledDocument sDoc = (StyledDocument)doc;
0N/A Element elem = sDoc.getCharacterElement(c.composedTextStart.getOffset());
0N/A AttributeSet attr = elem.getAttributes();
0N/A bg = sDoc.getBackground(attr);
0N/A }
0N/A
0N/A if (bg == null) {
0N/A bg = c.getBackground();
0N/A }
0N/A }
0N/A
0N/A //
0N/A // Draw caret in XOR mode.
0N/A //
0N/A public void paint(Graphics g) {
0N/A if(isVisible()) {
0N/A try {
0N/A Rectangle r = component.modelToView(getDot());
0N/A g.setXORMode(bg);
0N/A g.drawLine(r.x, r.y, r.x, r.y + r.height - 1);
0N/A g.setPaintMode();
0N/A } catch (BadLocationException e) {
0N/A // can't render I guess
0N/A //System.err.println("Can't render cursor");
0N/A }
0N/A }
0N/A }
0N/A
0N/A //
0N/A // If some area other than the composed text is clicked by mouse,
0N/A // issue endComposition() to force commit the composed text.
0N/A //
0N/A protected void positionCaret(MouseEvent me) {
0N/A JTextComponent host = component;
0N/A Point pt = new Point(me.getX(), me.getY());
0N/A int offset = host.viewToModel(pt);
0N/A int composedStartIndex = host.composedTextStart.getOffset();
0N/A if ((offset < composedStartIndex) ||
0N/A (offset > composedTextEnd.getOffset())) {
0N/A try {
0N/A // Issue endComposition
0N/A Position newPos = host.getDocument().createPosition(offset);
0N/A host.getInputContext().endComposition();
0N/A
0N/A // Post a caret positioning runnable to assure that the positioning
0N/A // occurs *after* committing the composed text.
0N/A EventQueue.invokeLater(new DoSetCaretPosition(host, newPos));
0N/A } catch (BadLocationException ble) {
0N/A System.err.println(ble);
0N/A }
0N/A } else {
0N/A // Normal processing
0N/A super.positionCaret(me);
0N/A }
0N/A }
0N/A }
0N/A
0N/A //
0N/A // Runnable class for invokeLater() to set caret position later.
0N/A //
0N/A private class DoSetCaretPosition implements Runnable {
0N/A JTextComponent host;
0N/A Position newPos;
0N/A
0N/A DoSetCaretPosition(JTextComponent host, Position newPos) {
0N/A this.host = host;
0N/A this.newPos = newPos;
0N/A }
0N/A
0N/A public void run() {
0N/A host.setCaretPosition(newPos.getOffset());
0N/A }
0N/A }
0N/A}