5567 lines · 206.6 KB · Java
RawDownload
/* * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation.  Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */package javax.swing;  import java.util.HashSet;import java.util.Hashtable;import java.util.Dictionary;import java.util.Enumeration;import java.util.Locale;import java.util.Vector;import java.util.EventListener;import java.util.Set;import java.util.Map;import java.util.HashMap; import java.awt.*;import java.awt.event.*;import java.awt.image.VolatileImage;import java.awt.Graphics2D;import java.awt.peer.LightweightPeer;import java.awt.dnd.DropTarget;import java.awt.font.FontRenderContext;import java.beans.PropertyChangeListener;import java.beans.VetoableChangeListener;import java.beans.VetoableChangeSupport;import java.beans.Transient; import java.applet.Applet; import java.io.Serializable;import java.io.ObjectOutputStream;import java.io.ObjectInputStream;import java.io.IOException;import java.io.ObjectInputValidation;import java.io.InvalidObjectException; import javax.swing.border.*;import javax.swing.event.*;import javax.swing.plaf.*;import static javax.swing.ClientPropertyKey.*;import javax.accessibility.*; import sun.swing.SwingUtilities2;import sun.swing.UIClientPropertyKey; /** * The base class for all Swing components except top-level containers. * To use a component that inherits from <code>JComponent</code>, * you must place the component in a containment hierarchy * whose root is a top-level Swing container. * Top-level Swing containers -- * such as <code>JFrame</code>, <code>JDialog</code>, * and <code>JApplet</code> -- * are specialized components * that provide a place for other Swing components to paint themselves. * For an explanation of containment hierarchies, see * <a href="http://java.sun.com/docs/books/tutorial/uiswing/overview/hierarchy.html">Swing Components and the Containment Hierarchy</a>, * a section in <em>The Java Tutorial</em>. * * <p> * The <code>JComponent</code> class provides: * <ul> * <li>The base class for both standard and custom components *     that use the Swing architecture. * <li>A "pluggable look and feel" (L&F) that can be specified by the *     programmer or (optionally) selected by the user at runtime. *     The look and feel for each component is provided by a *     <em>UI delegate</em> -- an object that descends from *     {@link javax.swing.plaf.ComponentUI}. *     See <a * href="http://java.sun.com/docs/books/tutorial/uiswing/misc/plaf.html">How *     to Set the Look and Feel</a> *     in <em>The Java Tutorial</em> *     for more information. * <li>Comprehensive keystroke handling. *     See the document <a * href="http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html">Keyboard *     Bindings in Swing</a>, *     an article in <em>The Swing Connection</em>, *     for more information. * <li>Support for tool tips -- *     short descriptions that pop up when the cursor lingers *     over a component. *     See <a * href="http://java.sun.com/docs/books/tutorial/uiswing/components/tooltip.html">How *     to Use Tool Tips</a> *     in <em>The Java Tutorial</em> *     for more information. * <li>Support for accessibility. *     <code>JComponent</code> contains all of the methods in the *     <code>Accessible</code> interface, *     but it doesn't actually implement the interface.  That is the *     responsibility of the individual classes *     that extend <code>JComponent</code>. * <li>Support for component-specific properties. *     With the {@link #putClientProperty} *     and {@link #getClientProperty} methods, *     you can associate name-object pairs *     with any object that descends from <code>JComponent</code>. * <li>An infrastructure for painting *     that includes double buffering and support for borders. *     For more information see <a * href="http://java.sun.com/docs/books/tutorial/uiswing/overview/draw.html">Painting</a> and * <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/border.html">How *     to Use Borders</a>, *     both of which are sections in <em>The Java Tutorial</em>. * </ul> * For more information on these subjects, see the * <a href="package-summary.html#package_description">Swing package description</a> * and <em>The Java Tutorial</em> section * <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/jcomponent.html">The JComponent Class</a>. * <p> * <code>JComponent</code> and its subclasses document default values * for certain properties.  For example, <code>JTable</code> documents the * default row height as 16.  Each <code>JComponent</code> subclass * that has a <code>ComponentUI</code> will create the * <code>ComponentUI</code> as part of its constructor.  In order * to provide a particular look and feel each * <code>ComponentUI</code> may set properties back on the * <code>JComponent</code> that created it.  For example, a custom * look and feel may require <code>JTable</code>s to have a row * height of 24. The documented defaults are the value of a property * BEFORE the <code>ComponentUI</code> has been installed.  If you * need a specific value for a particular property you should * explicitly set it. * <p> * In release 1.4, the focus subsystem was rearchitected. * For more information, see * <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html"> * How to Use the Focus Subsystem</a>, * a section in <em>The Java Tutorial</em>. * <p> * <strong>Warning:</strong> Swing is not thread safe. For more * information see <a * href="package-summary.html#threading">Swing's Threading * Policy</a>. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing.  As of 1.4, support for long term storage * of all JavaBeans<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @see KeyStroke * @see Action * @see #setBorder * @see #registerKeyboardAction * @see JOptionPane * @see #setDebugGraphicsOptions * @see #setToolTipText * @see #setAutoscrolls * * @author Hans Muller * @author Arnaud Weber */public abstract class JComponent extends Container implements Serializable,                                              TransferHandler.HasGetTransferHandler{    /**     * @see #getUIClassID     * @see #writeObject     */    private static final String uiClassID = "ComponentUI";     /**     * @see #readObject     */    private static final Hashtable<ObjectInputStream, ReadObjectCallback> readObjectCallbacks =            new Hashtable<ObjectInputStream, ReadObjectCallback>(1);     /**     * Keys to use for forward focus traversal when the JComponent is     * managing focus.     */    private static Set<KeyStroke> managingFocusForwardTraversalKeys;     /**     * Keys to use for backward focus traversal when the JComponent is     * managing focus.     */    private static Set<KeyStroke> managingFocusBackwardTraversalKeys;     // Following are the possible return values from getObscuredState.    private static final int NOT_OBSCURED = 0;    private static final int PARTIALLY_OBSCURED = 1;    private static final int COMPLETELY_OBSCURED = 2;     /**     * Set to true when DebugGraphics has been loaded.     */    static boolean DEBUG_GRAPHICS_LOADED;     /**     * Key used to look up a value from the AppContext to determine the     * JComponent the InputVerifier is running for. That is, if     * AppContext.get(INPUT_VERIFIER_SOURCE_KEY) returns non-null, it     * indicates the EDT is calling into the InputVerifier from the     * returned component.     */    private static final Object INPUT_VERIFIER_SOURCE_KEY =            new StringBuilder("InputVerifierSourceKey");     /* The following fields support set methods for the corresponding     * java.awt.Component properties.     */    private boolean isAlignmentXSet;    private float alignmentX;    private boolean isAlignmentYSet;    private float alignmentY;     /**     * Backing store for JComponent properties and listeners     */     /** The look and feel delegate for this component. */    protected transient ComponentUI ui;    /** A list of event listeners for this component. */    protected EventListenerList listenerList = new EventListenerList();     private transient ArrayTable clientProperties;    private VetoableChangeSupport vetoableChangeSupport;    /**     * Whether or not autoscroll has been enabled.     */    private boolean autoscrolls;    private Border border;    private int flags;     /* Input verifier for this component */    private InputVerifier inputVerifier = null;     private boolean verifyInputWhenFocusTarget = true;     /**     * Set in <code>_paintImmediately</code>.     * Will indicate the child that initiated the painting operation.     * If <code>paintingChild</code> is opaque, no need to paint     * any child components after <code>paintingChild</code>.     * Test used in <code>paintChildren</code>.     */    transient Component         paintingChild;     /**     * Constant used for <code>registerKeyboardAction</code> that     * means that the command should be invoked when     * the component has the focus.     */    public static final int WHEN_FOCUSED = 0;     /**     * Constant used for <code>registerKeyboardAction</code> that     * means that the command should be invoked when the receiving     * component is an ancestor of the focused component or is     * itself the focused component.     */    public static final int WHEN_ANCESTOR_OF_FOCUSED_COMPONENT = 1;     /**     * Constant used for <code>registerKeyboardAction</code> that     * means that the command should be invoked when     * the receiving component is in the window that has the focus     * or is itself the focused component.     */    public static final int WHEN_IN_FOCUSED_WINDOW = 2;     /**     * Constant used by some of the APIs to mean that no condition is defined.     */    public static final int UNDEFINED_CONDITION = -1;     /**     * The key used by <code>JComponent</code> to access keyboard bindings.     */    private static final String KEYBOARD_BINDINGS_KEY = "_KeyboardBindings";     /**     * An array of <code>KeyStroke</code>s used for     * <code>WHEN_IN_FOCUSED_WINDOW</code> are stashed     * in the client properties under this string.     */    private static final String WHEN_IN_FOCUSED_WINDOW_BINDINGS = "_WhenInFocusedWindow";     /**     * The comment to display when the cursor is over the component,     * also known as a "value tip", "flyover help", or "flyover label".     */    public static final String TOOL_TIP_TEXT_KEY = "ToolTipText";     private static final String NEXT_FOCUS = "nextFocus";     /**     * <code>JPopupMenu</code> assigned to this component     * and all of its childrens     */    private JPopupMenu popupMenu;     /** Private flags **/    private static final int IS_DOUBLE_BUFFERED                       =  0;    private static final int ANCESTOR_USING_BUFFER                    =  1;    private static final int IS_PAINTING_TILE                         =  2;    private static final int IS_OPAQUE                                =  3;    private static final int KEY_EVENTS_ENABLED                       =  4;    private static final int FOCUS_INPUTMAP_CREATED                   =  5;    private static final int ANCESTOR_INPUTMAP_CREATED                =  6;    private static final int WIF_INPUTMAP_CREATED                     =  7;    private static final int ACTIONMAP_CREATED                        =  8;    private static final int CREATED_DOUBLE_BUFFER                    =  9;    // bit 10 is free    private static final int IS_PRINTING                              = 11;    private static final int IS_PRINTING_ALL                          = 12;    private static final int IS_REPAINTING                            = 13;    /** Bits 14-21 are used to handle nested writeObject calls. **/    private static final int WRITE_OBJ_COUNTER_FIRST                  = 14;    private static final int RESERVED_1                               = 15;    private static final int RESERVED_2                               = 16;    private static final int RESERVED_3                               = 17;    private static final int RESERVED_4                               = 18;    private static final int RESERVED_5                               = 19;    private static final int RESERVED_6                               = 20;    private static final int WRITE_OBJ_COUNTER_LAST                   = 21;     private static final int REQUEST_FOCUS_DISABLED                   = 22;    private static final int INHERITS_POPUP_MENU                      = 23;    private static final int OPAQUE_SET                               = 24;    private static final int AUTOSCROLLS_SET                          = 25;    private static final int FOCUS_TRAVERSAL_KEYS_FORWARD_SET         = 26;    private static final int FOCUS_TRAVERSAL_KEYS_BACKWARD_SET        = 27;    private static final int REVALIDATE_RUNNABLE_SCHEDULED            = 28;     /**     * Temporary rectangles.     */    private static java.util.List<Rectangle> tempRectangles = new java.util.ArrayList<Rectangle>(11);     /** Used for <code>WHEN_FOCUSED</code> bindings. */    private InputMap focusInputMap;    /** Used for <code>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT</code> bindings. */    private InputMap ancestorInputMap;    /** Used for <code>WHEN_IN_FOCUSED_KEY</code> bindings. */    private ComponentInputMap windowInputMap;     /** ActionMap. */    private ActionMap actionMap;     /** Key used to store the default locale in an AppContext **/    private static final String defaultLocale = "JComponent.defaultLocale";     private static Component componentObtainingGraphicsFrom;    private static Object componentObtainingGraphicsFromLock = new            StringBuilder("componentObtainingGraphicsFrom");     /**     * AA text hints.     */    transient private Object aaTextInfo;     static Graphics safelyGetGraphics(Component c) {        return safelyGetGraphics(c, SwingUtilities.getRoot(c));    }     static Graphics safelyGetGraphics(Component c, Component root) {        synchronized(componentObtainingGraphicsFromLock) {            componentObtainingGraphicsFrom = root;            Graphics g = c.getGraphics();            componentObtainingGraphicsFrom = null;            return g;        }    }     static void getGraphicsInvoked(Component root) {        if (!JComponent.isComponentObtainingGraphicsFrom(root)) {            JRootPane rootPane = ((RootPaneContainer)root).getRootPane();            if (rootPane != null) {                rootPane.disableTrueDoubleBuffering();            }        }    }      /**     * Returns true if {@code c} is the component the graphics is being     * requested of. This is intended for use when getGraphics is invoked.     */    private static boolean isComponentObtainingGraphicsFrom(Component c) {        synchronized(componentObtainingGraphicsFromLock) {            return (componentObtainingGraphicsFrom == c);        }    }     /**     * Returns the Set of <code>KeyStroke</code>s to use if the component     * is managing focus for forward focus traversal.     */    static Set<KeyStroke> getManagingFocusForwardTraversalKeys() {        synchronized(JComponent.class) {            if (managingFocusForwardTraversalKeys == null) {                managingFocusForwardTraversalKeys = new HashSet<KeyStroke>(1);                managingFocusForwardTraversalKeys.add(                    KeyStroke.getKeyStroke(KeyEvent.VK_TAB,                                           InputEvent.CTRL_MASK));            }        }        return managingFocusForwardTraversalKeys;    }     /**     * Returns the Set of <code>KeyStroke</code>s to use if the component     * is managing focus for backward focus traversal.     */    static Set<KeyStroke> getManagingFocusBackwardTraversalKeys() {        synchronized(JComponent.class) {            if (managingFocusBackwardTraversalKeys == null) {                managingFocusBackwardTraversalKeys = new HashSet<KeyStroke>(1);                managingFocusBackwardTraversalKeys.add(                    KeyStroke.getKeyStroke(KeyEvent.VK_TAB,                                           InputEvent.SHIFT_MASK |                                           InputEvent.CTRL_MASK));            }        }        return managingFocusBackwardTraversalKeys;    }     private static Rectangle fetchRectangle() {        synchronized(tempRectangles) {            Rectangle rect;            int size = tempRectangles.size();            if (size > 0) {                rect = tempRectangles.remove(size - 1);            }            else {                rect = new Rectangle(0, 0, 0, 0);            }            return rect;        }    }     private static void recycleRectangle(Rectangle rect) {        synchronized(tempRectangles) {            tempRectangles.add(rect);        }    }     /**     * Sets whether or not <code>getComponentPopupMenu</code> should delegate     * to the parent if this component does not have a <code>JPopupMenu</code>     * assigned to it.     * <p>     * The default value for this is false, but some <code>JComponent</code>     * subclasses that are implemented as a number of <code>JComponent</code>s     * may set this to true.     * <p>     * This is a bound property.     *     * @param value whether or not the JPopupMenu is inherited     * @see #setComponentPopupMenu     * @beaninfo     *        bound: true     *  description: Whether or not the JPopupMenu is inherited     * @since 1.5     */    public void setInheritsPopupMenu(boolean value) {        boolean oldValue = getFlag(INHERITS_POPUP_MENU);        setFlag(INHERITS_POPUP_MENU, value);        firePropertyChange("inheritsPopupMenu", oldValue, value);    }     /**     * Returns true if the JPopupMenu should be inherited from the parent.     *     * @see #setComponentPopupMenu     * @since 1.5     */    public boolean getInheritsPopupMenu() {

Lines 1–500 of 5567.