1 /*
   2  * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package javax.swing;
  26 
  27 
  28 import java.util.HashSet;
  29 import java.util.Hashtable;
  30 import java.util.Dictionary;
  31 import java.util.Enumeration;
  32 import java.util.Locale;
  33 import java.util.Vector;
  34 import java.util.EventListener;
  35 import java.util.Set;
  36 import java.util.Map;
  37 import java.util.HashMap;
  38 
  39 import java.awt.*;
  40 import java.awt.event.*;
  41 import java.awt.image.VolatileImage;
  42 import java.awt.Graphics2D;
  43 import java.awt.peer.LightweightPeer;
  44 import java.awt.dnd.DropTarget;
  45 import java.awt.font.FontRenderContext;
  46 import java.beans.PropertyChangeListener;
  47 import java.beans.VetoableChangeListener;
  48 import java.beans.VetoableChangeSupport;
  49 import java.beans.Transient;
  50 
  51 import java.applet.Applet;
  52 
  53 import java.io.Serializable;
  54 import java.io.ObjectOutputStream;
  55 import java.io.ObjectInputStream;
  56 import java.io.IOException;
  57 import java.io.ObjectInputValidation;
  58 import java.io.InvalidObjectException;
  59 
  60 import javax.swing.border.*;
  61 import javax.swing.event.*;
  62 import javax.swing.plaf.*;
  63 import static javax.swing.ClientPropertyKey.*;
  64 import javax.accessibility.*;
  65 
  66 import sun.swing.SwingUtilities2;
  67 import sun.swing.UIClientPropertyKey;
  68 
  69 /**
  70  * The base class for all Swing components except top-level containers.
  71  * To use a component that inherits from <code>JComponent</code>,
  72  * you must place the component in a containment hierarchy
  73  * whose root is a top-level Swing container.
  74  * Top-level Swing containers --
  75  * such as <code>JFrame</code>, <code>JDialog</code>,
  76  * and <code>JApplet</code> --
  77  * are specialized components
  78  * that provide a place for other Swing components to paint themselves.
  79  * For an explanation of containment hierarchies, see
  80  * <a
  81  href="http://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html">Swing Components and the Containment Hierarchy</a>,
  82  * a section in <em>The Java Tutorial</em>.
  83  *
  84  * <p>
  85  * The <code>JComponent</code> class provides:
  86  * <ul>
  87  * <li>The base class for both standard and custom components
  88  *     that use the Swing architecture.
  89  * <li>A "pluggable look and feel" (L&amp;F) that can be specified by the
  90  *     programmer or (optionally) selected by the user at runtime.
  91  *     The look and feel for each component is provided by a
  92  *     <em>UI delegate</em> -- an object that descends from
  93  *     {@link javax.swing.plaf.ComponentUI}.
  94  *     See <a
  95  * href="http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html">How
  96  *     to Set the Look and Feel</a>
  97  *     in <em>The Java Tutorial</em>
  98  *     for more information.
  99  * <li>Comprehensive keystroke handling.
 100  *     See the document <a
 101  * href="http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html">How to Use Key Bindings</a>,
 102  *     an article in <em>The Java Tutorial</em>,
 103  *     for more information.
 104  * <li>Support for tool tips --
 105  *     short descriptions that pop up when the cursor lingers
 106  *     over a component.
 107  *     See <a
 108  * href="http://docs.oracle.com/javase/tutorial/uiswing/components/tooltip.html">How
 109  *     to Use Tool Tips</a>
 110  *     in <em>The Java Tutorial</em>
 111  *     for more information.
 112  * <li>Support for accessibility.
 113  *     <code>JComponent</code> contains all of the methods in the
 114  *     <code>Accessible</code> interface,
 115  *     but it doesn't actually implement the interface.  That is the
 116  *     responsibility of the individual classes
 117  *     that extend <code>JComponent</code>.
 118  * <li>Support for component-specific properties.
 119  *     With the {@link #putClientProperty}
 120  *     and {@link #getClientProperty} methods,
 121  *     you can associate name-object pairs
 122  *     with any object that descends from <code>JComponent</code>.
 123  * <li>An infrastructure for painting
 124  *     that includes double buffering and support for borders.
 125  *     For more information see <a
 126  * href="http://www.oracle.com/technetwork/java/painting-140037.html#swing">Painting</a> and
 127  * <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/border.htmll">How
 128  *     to Use Borders</a>,
 129  *     both of which are sections in <em>The Java Tutorial</em>.
 130  * </ul>
 131  * For more information on these subjects, see the
 132  * <a href="package-summary.html#package_description">Swing package description</a>
 133  * and <em>The Java Tutorial</em> section
 134  * <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/jcomponent.html">The JComponent Class</a>.
 135  * <p>
 136  * <code>JComponent</code> and its subclasses document default values
 137  * for certain properties.  For example, <code>JTable</code> documents the
 138  * default row height as 16.  Each <code>JComponent</code> subclass
 139  * that has a <code>ComponentUI</code> will create the
 140  * <code>ComponentUI</code> as part of its constructor.  In order
 141  * to provide a particular look and feel each
 142  * <code>ComponentUI</code> may set properties back on the
 143  * <code>JComponent</code> that created it.  For example, a custom
 144  * look and feel may require <code>JTable</code>s to have a row
 145  * height of 24. The documented defaults are the value of a property
 146  * BEFORE the <code>ComponentUI</code> has been installed.  If you
 147  * need a specific value for a particular property you should
 148  * explicitly set it.
 149  * <p>
 150  * In release 1.4, the focus subsystem was rearchitected.
 151  * For more information, see
 152  * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
 153  * How to Use the Focus Subsystem</a>,
 154  * a section in <em>The Java Tutorial</em>.
 155  * <p>
 156  * <strong>Warning:</strong> Swing is not thread safe. For more
 157  * information see <a
 158  * href="package-summary.html#threading">Swing's Threading
 159  * Policy</a>.
 160  * <p>
 161  * <strong>Warning:</strong>
 162  * Serialized objects of this class will not be compatible with
 163  * future Swing releases. The current serialization support is
 164  * appropriate for short term storage or RMI between applications running
 165  * the same version of Swing.  As of 1.4, support for long term storage
 166  * of all JavaBeans&trade;
 167  * has been added to the <code>java.beans</code> package.
 168  * Please see {@link java.beans.XMLEncoder}.
 169  *
 170  * @see KeyStroke
 171  * @see Action
 172  * @see #setBorder
 173  * @see #registerKeyboardAction
 174  * @see JOptionPane
 175  * @see #setDebugGraphicsOptions
 176  * @see #setToolTipText
 177  * @see #setAutoscrolls
 178  *
 179  * @author Hans Muller
 180  * @author Arnaud Weber
 181  */
 182 @SuppressWarnings("serial") // Same-version serialization only
 183 public abstract class JComponent extends Container implements Serializable,
 184                                               TransferHandler.HasGetTransferHandler
 185 {
 186     /**
 187      * @see #getUIClassID
 188      * @see #writeObject
 189      */
 190     private static final String uiClassID = "ComponentUI";
 191 
 192     /**
 193      * @see #readObject
 194      */
 195     private static final Hashtable<ObjectInputStream, ReadObjectCallback> readObjectCallbacks =
 196             new Hashtable<ObjectInputStream, ReadObjectCallback>(1);
 197 
 198     /**
 199      * Keys to use for forward focus traversal when the JComponent is
 200      * managing focus.
 201      */
 202     private static Set<KeyStroke> managingFocusForwardTraversalKeys;
 203 
 204     /**
 205      * Keys to use for backward focus traversal when the JComponent is
 206      * managing focus.
 207      */
 208     private static Set<KeyStroke> managingFocusBackwardTraversalKeys;
 209 
 210     // Following are the possible return values from getObscuredState.
 211     private static final int NOT_OBSCURED = 0;
 212     private static final int PARTIALLY_OBSCURED = 1;
 213     private static final int COMPLETELY_OBSCURED = 2;
 214 
 215     /**
 216      * Set to true when DebugGraphics has been loaded.
 217      */
 218     static boolean DEBUG_GRAPHICS_LOADED;
 219 
 220     /**
 221      * Key used to look up a value from the AppContext to determine the
 222      * JComponent the InputVerifier is running for. That is, if
 223      * AppContext.get(INPUT_VERIFIER_SOURCE_KEY) returns non-null, it
 224      * indicates the EDT is calling into the InputVerifier from the
 225      * returned component.
 226      */
 227     private static final Object INPUT_VERIFIER_SOURCE_KEY =
 228             new StringBuilder("InputVerifierSourceKey");
 229 
 230     /* The following fields support set methods for the corresponding
 231      * java.awt.Component properties.
 232      */
 233     private boolean isAlignmentXSet;
 234     private float alignmentX;
 235     private boolean isAlignmentYSet;
 236     private float alignmentY;
 237 
 238     /**
 239      * Backing store for JComponent properties and listeners
 240      */
 241 
 242     /** The look and feel delegate for this component. */
 243     protected transient ComponentUI ui;
 244     /** A list of event listeners for this component. */
 245     protected EventListenerList listenerList = new EventListenerList();
 246 
 247     private transient ArrayTable clientProperties;
 248     private VetoableChangeSupport vetoableChangeSupport;
 249     /**
 250      * Whether or not autoscroll has been enabled.
 251      */
 252     private boolean autoscrolls;
 253     private Border border;
 254     private int flags;
 255 
 256     /* Input verifier for this component */
 257     private InputVerifier inputVerifier = null;
 258 
 259     private boolean verifyInputWhenFocusTarget = true;
 260 
 261     /**
 262      * Set in <code>_paintImmediately</code>.
 263      * Will indicate the child that initiated the painting operation.
 264      * If <code>paintingChild</code> is opaque, no need to paint
 265      * any child components after <code>paintingChild</code>.
 266      * Test used in <code>paintChildren</code>.
 267      */
 268     transient Component         paintingChild;
 269 
 270     /**
 271      * Constant used for <code>registerKeyboardAction</code> that
 272      * means that the command should be invoked when
 273      * the component has the focus.
 274      */
 275     public static final int WHEN_FOCUSED = 0;
 276 
 277     /**
 278      * Constant used for <code>registerKeyboardAction</code> that
 279      * means that the command should be invoked when the receiving
 280      * component is an ancestor of the focused component or is
 281      * itself the focused component.
 282      */
 283     public static final int WHEN_ANCESTOR_OF_FOCUSED_COMPONENT = 1;
 284 
 285     /**
 286      * Constant used for <code>registerKeyboardAction</code> that
 287      * means that the command should be invoked when
 288      * the receiving component is in the window that has the focus
 289      * or is itself the focused component.
 290      */
 291     public static final int WHEN_IN_FOCUSED_WINDOW = 2;
 292 
 293     /**
 294      * Constant used by some of the APIs to mean that no condition is defined.
 295      */
 296     public static final int UNDEFINED_CONDITION = -1;
 297 
 298     /**
 299      * The key used by <code>JComponent</code> to access keyboard bindings.
 300      */
 301     private static final String KEYBOARD_BINDINGS_KEY = "_KeyboardBindings";
 302 
 303     /**
 304      * An array of <code>KeyStroke</code>s used for
 305      * <code>WHEN_IN_FOCUSED_WINDOW</code> are stashed
 306      * in the client properties under this string.
 307      */
 308     private static final String WHEN_IN_FOCUSED_WINDOW_BINDINGS = "_WhenInFocusedWindow";
 309 
 310     /**
 311      * The comment to display when the cursor is over the component,
 312      * also known as a "value tip", "flyover help", or "flyover label".
 313      */
 314     public static final String TOOL_TIP_TEXT_KEY = "ToolTipText";
 315 
 316     private static final String NEXT_FOCUS = "nextFocus";
 317 
 318     /**
 319      * <code>JPopupMenu</code> assigned to this component
 320      * and all of its children
 321      */
 322     private JPopupMenu popupMenu;
 323 
 324     /** Private flags **/
 325     private static final int IS_DOUBLE_BUFFERED                       =  0;
 326     private static final int ANCESTOR_USING_BUFFER                    =  1;
 327     private static final int IS_PAINTING_TILE                         =  2;
 328     private static final int IS_OPAQUE                                =  3;
 329     private static final int KEY_EVENTS_ENABLED                       =  4;
 330     private static final int FOCUS_INPUTMAP_CREATED                   =  5;
 331     private static final int ANCESTOR_INPUTMAP_CREATED                =  6;
 332     private static final int WIF_INPUTMAP_CREATED                     =  7;
 333     private static final int ACTIONMAP_CREATED                        =  8;
 334     private static final int CREATED_DOUBLE_BUFFER                    =  9;
 335     // bit 10 is free
 336     private static final int IS_PRINTING                              = 11;
 337     private static final int IS_PRINTING_ALL                          = 12;
 338     private static final int IS_REPAINTING                            = 13;
 339     /** Bits 14-21 are used to handle nested writeObject calls. **/
 340     private static final int WRITE_OBJ_COUNTER_FIRST                  = 14;
 341     private static final int RESERVED_1                               = 15;
 342     private static final int RESERVED_2                               = 16;
 343     private static final int RESERVED_3                               = 17;
 344     private static final int RESERVED_4                               = 18;
 345     private static final int RESERVED_5                               = 19;
 346     private static final int RESERVED_6                               = 20;
 347     private static final int WRITE_OBJ_COUNTER_LAST                   = 21;
 348 
 349     private static final int REQUEST_FOCUS_DISABLED                   = 22;
 350     private static final int INHERITS_POPUP_MENU                      = 23;
 351     private static final int OPAQUE_SET                               = 24;
 352     private static final int AUTOSCROLLS_SET                          = 25;
 353     private static final int FOCUS_TRAVERSAL_KEYS_FORWARD_SET         = 26;
 354     private static final int FOCUS_TRAVERSAL_KEYS_BACKWARD_SET        = 27;
 355     private static final int REVALIDATE_RUNNABLE_SCHEDULED            = 28;
 356 
 357     /**
 358      * Temporary rectangles.
 359      */
 360     private static java.util.List<Rectangle> tempRectangles = new java.util.ArrayList<Rectangle>(11);
 361 
 362     /** Used for <code>WHEN_FOCUSED</code> bindings. */
 363     private InputMap focusInputMap;
 364     /** Used for <code>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT</code> bindings. */
 365     private InputMap ancestorInputMap;
 366     /** Used for <code>WHEN_IN_FOCUSED_KEY</code> bindings. */
 367     private ComponentInputMap windowInputMap;
 368 
 369     /** ActionMap. */
 370     private ActionMap actionMap;
 371 
 372     /** Key used to store the default locale in an AppContext **/
 373     private static final String defaultLocale = "JComponent.defaultLocale";
 374 
 375     private static Component componentObtainingGraphicsFrom;
 376     private static Object componentObtainingGraphicsFromLock = new
 377             StringBuilder("componentObtainingGraphicsFrom");
 378 
 379     /**
 380      * AA text hints.
 381      */
 382     transient private Object aaTextInfo;
 383 
 384     static Graphics safelyGetGraphics(Component c) {
 385         return safelyGetGraphics(c, SwingUtilities.getRoot(c));
 386     }
 387 
 388     static Graphics safelyGetGraphics(Component c, Component root) {
 389         synchronized(componentObtainingGraphicsFromLock) {
 390             componentObtainingGraphicsFrom = root;
 391             Graphics g = c.getGraphics();
 392             componentObtainingGraphicsFrom = null;
 393             return g;
 394         }
 395     }
 396 
 397     static void getGraphicsInvoked(Component root) {
 398         if (!JComponent.isComponentObtainingGraphicsFrom(root)) {
 399             JRootPane rootPane = ((RootPaneContainer)root).getRootPane();
 400             if (rootPane != null) {
 401                 rootPane.disableTrueDoubleBuffering();
 402             }
 403         }
 404     }
 405 
 406 
 407     /**
 408      * Returns true if {@code c} is the component the graphics is being
 409      * requested of. This is intended for use when getGraphics is invoked.
 410      */
 411     private static boolean isComponentObtainingGraphicsFrom(Component c) {
 412         synchronized(componentObtainingGraphicsFromLock) {
 413             return (componentObtainingGraphicsFrom == c);
 414         }
 415     }
 416 
 417     /**
 418      * Returns the Set of <code>KeyStroke</code>s to use if the component
 419      * is managing focus for forward focus traversal.
 420      */
 421     static Set<KeyStroke> getManagingFocusForwardTraversalKeys() {
 422         synchronized(JComponent.class) {
 423             if (managingFocusForwardTraversalKeys == null) {
 424                 managingFocusForwardTraversalKeys = new HashSet<KeyStroke>(1);
 425                 managingFocusForwardTraversalKeys.add(
 426                     KeyStroke.getKeyStroke(KeyEvent.VK_TAB,
 427                                            InputEvent.CTRL_MASK));
 428             }
 429         }
 430         return managingFocusForwardTraversalKeys;
 431     }
 432 
 433     /**
 434      * Returns the Set of <code>KeyStroke</code>s to use if the component
 435      * is managing focus for backward focus traversal.
 436      */
 437     static Set<KeyStroke> getManagingFocusBackwardTraversalKeys() {
 438         synchronized(JComponent.class) {
 439             if (managingFocusBackwardTraversalKeys == null) {
 440                 managingFocusBackwardTraversalKeys = new HashSet<KeyStroke>(1);
 441                 managingFocusBackwardTraversalKeys.add(
 442                     KeyStroke.getKeyStroke(KeyEvent.VK_TAB,
 443                                            InputEvent.SHIFT_MASK |
 444                                            InputEvent.CTRL_MASK));
 445             }
 446         }
 447         return managingFocusBackwardTraversalKeys;
 448     }
 449 
 450     private static Rectangle fetchRectangle() {
 451         synchronized(tempRectangles) {
 452             Rectangle rect;
 453             int size = tempRectangles.size();
 454             if (size > 0) {
 455                 rect = tempRectangles.remove(size - 1);
 456             }
 457             else {
 458                 rect = new Rectangle(0, 0, 0, 0);
 459             }
 460             return rect;
 461         }
 462     }
 463 
 464     private static void recycleRectangle(Rectangle rect) {
 465         synchronized(tempRectangles) {
 466             tempRectangles.add(rect);
 467         }
 468     }
 469 
 470     /**
 471      * Sets whether or not <code>getComponentPopupMenu</code> should delegate
 472      * to the parent if this component does not have a <code>JPopupMenu</code>
 473      * assigned to it.
 474      * <p>
 475      * The default value for this is false, but some <code>JComponent</code>
 476      * subclasses that are implemented as a number of <code>JComponent</code>s
 477      * may set this to true.
 478      * <p>
 479      * This is a bound property.
 480      *
 481      * @param value whether or not the JPopupMenu is inherited
 482      * @see #setComponentPopupMenu
 483      * @beaninfo
 484      *        bound: true
 485      *  description: Whether or not the JPopupMenu is inherited
 486      * @since 1.5
 487      */
 488     public void setInheritsPopupMenu(boolean value) {
 489         boolean oldValue = getFlag(INHERITS_POPUP_MENU);
 490         setFlag(INHERITS_POPUP_MENU, value);
 491         firePropertyChange("inheritsPopupMenu", oldValue, value);
 492     }
 493 
 494     /**
 495      * Returns true if the JPopupMenu should be inherited from the parent.
 496      *
 497      * @see #setComponentPopupMenu
 498      * @since 1.5
 499      */
 500     public boolean getInheritsPopupMenu() {
 501         return getFlag(INHERITS_POPUP_MENU);
 502     }
 503 
 504     /**
 505      * Sets the <code>JPopupMenu</code> for this <code>JComponent</code>.
 506      * The UI is responsible for registering bindings and adding the necessary
 507      * listeners such that the <code>JPopupMenu</code> will be shown at
 508      * the appropriate time. When the <code>JPopupMenu</code> is shown
 509      * depends upon the look and feel: some may show it on a mouse event,
 510      * some may enable a key binding.
 511      * <p>
 512      * If <code>popup</code> is null, and <code>getInheritsPopupMenu</code>
 513      * returns true, then <code>getComponentPopupMenu</code> will be delegated
 514      * to the parent. This provides for a way to make all child components
 515      * inherit the popupmenu of the parent.
 516      * <p>
 517      * This is a bound property.
 518      *
 519      * @param popup - the popup that will be assigned to this component
 520      *                may be null
 521      * @see #getComponentPopupMenu
 522      * @beaninfo
 523      *        bound: true
 524      *    preferred: true
 525      *  description: Popup to show
 526      * @since 1.5
 527      */
 528     public void setComponentPopupMenu(JPopupMenu popup) {
 529         if(popup != null) {
 530             enableEvents(AWTEvent.MOUSE_EVENT_MASK);
 531         }
 532         JPopupMenu oldPopup = this.popupMenu;
 533         this.popupMenu = popup;
 534         firePropertyChange("componentPopupMenu", oldPopup, popup);
 535     }
 536 
 537     /**
 538      * Returns <code>JPopupMenu</code> that assigned for this component.
 539      * If this component does not have a <code>JPopupMenu</code> assigned
 540      * to it and <code>getInheritsPopupMenu</code> is true, this
 541      * will return <code>getParent().getComponentPopupMenu()</code> (assuming
 542      * the parent is valid.)
 543      *
 544      * @return <code>JPopupMenu</code> assigned for this component
 545      *         or <code>null</code> if no popup assigned
 546      * @see #setComponentPopupMenu
 547      * @since 1.5
 548      */
 549     public JPopupMenu getComponentPopupMenu() {
 550 
 551         if(!getInheritsPopupMenu()) {
 552             return popupMenu;
 553         }
 554 
 555         if(popupMenu == null) {
 556             // Search parents for its popup
 557             Container parent = getParent();
 558             while (parent != null) {
 559                 if(parent instanceof JComponent) {
 560                     return ((JComponent)parent).getComponentPopupMenu();
 561                 }
 562                 if(parent instanceof Window ||
 563                    parent instanceof Applet) {
 564                     // Reached toplevel, break and return null
 565                     break;
 566                 }
 567                 parent = parent.getParent();
 568             }
 569             return null;
 570         }
 571 
 572         return popupMenu;
 573     }
 574 
 575     /**
 576      * Default <code>JComponent</code> constructor.  This constructor does
 577      * very little initialization beyond calling the <code>Container</code>
 578      * constructor.  For example, the initial layout manager is
 579      * <code>null</code>. It does, however, set the component's locale
 580      * property to the value returned by
 581      * <code>JComponent.getDefaultLocale</code>.
 582      *
 583      * @see #getDefaultLocale
 584      */
 585     public JComponent() {
 586         super();
 587         // We enable key events on all JComponents so that accessibility
 588         // bindings will work everywhere. This is a partial fix to BugID
 589         // 4282211.
 590         enableEvents(AWTEvent.KEY_EVENT_MASK);
 591         if (isManagingFocus()) {
 592             LookAndFeel.installProperty(this,
 593                                         "focusTraversalKeysForward",
 594                                   getManagingFocusForwardTraversalKeys());
 595             LookAndFeel.installProperty(this,
 596                                         "focusTraversalKeysBackward",
 597                                   getManagingFocusBackwardTraversalKeys());
 598         }
 599 
 600         super.setLocale( JComponent.getDefaultLocale() );
 601     }
 602 
 603 
 604     /**
 605      * Resets the UI property to a value from the current look and feel.
 606      * <code>JComponent</code> subclasses must override this method
 607      * like this:
 608      * <pre>
 609      *   public void updateUI() {
 610      *      setUI((SliderUI)UIManager.getUI(this);
 611      *   }
 612      *  </pre>
 613      *
 614      * @see #setUI
 615      * @see UIManager#getLookAndFeel
 616      * @see UIManager#getUI
 617      */
 618     public void updateUI() {}
 619 
 620 
 621     /**
 622      * Sets the look and feel delegate for this component.
 623      * <code>JComponent</code> subclasses generally override this method
 624      * to narrow the argument type. For example, in <code>JSlider</code>:
 625      * <pre>
 626      * public void setUI(SliderUI newUI) {
 627      *     super.setUI(newUI);
 628      * }
 629      *  </pre>
 630      * <p>
 631      * Additionally <code>JComponent</code> subclasses must provide a
 632      * <code>getUI</code> method that returns the correct type.  For example:
 633      * <pre>
 634      * public SliderUI getUI() {
 635      *     return (SliderUI)ui;
 636      * }
 637      * </pre>
 638      *
 639      * @param newUI the new UI delegate
 640      * @see #updateUI
 641      * @see UIManager#getLookAndFeel
 642      * @see UIManager#getUI
 643      * @beaninfo
 644      *        bound: true
 645      *       hidden: true
 646      *    attribute: visualUpdate true
 647      *  description: The component's look and feel delegate.
 648      */
 649     protected void setUI(ComponentUI newUI) {
 650         /* We do not check that the UI instance is different
 651          * before allowing the switch in order to enable the
 652          * same UI instance *with different default settings*
 653          * to be installed.
 654          */
 655 
 656         uninstallUIAndProperties();
 657 
 658         // aaText shouldn't persist between look and feels, reset it.
 659         aaTextInfo =
 660             UIManager.getDefaults().get(SwingUtilities2.AA_TEXT_PROPERTY_KEY);
 661         ComponentUI oldUI = ui;
 662         ui = newUI;
 663         if (ui != null) {
 664             ui.installUI(this);
 665         }
 666 
 667         firePropertyChange("UI", oldUI, newUI);
 668         revalidate();
 669         repaint();
 670     }
 671 
 672     /**
 673      * Uninstalls the UI, if any, and any client properties designated
 674      * as being specific to the installed UI - instances of
 675      * {@code UIClientPropertyKey}.
 676      */
 677     private void uninstallUIAndProperties() {
 678         if (ui != null) {
 679             ui.uninstallUI(this);
 680             //clean UIClientPropertyKeys from client properties
 681             if (clientProperties != null) {
 682                 synchronized(clientProperties) {
 683                     Object[] clientPropertyKeys =
 684                         clientProperties.getKeys(null);
 685                     if (clientPropertyKeys != null) {
 686                         for (Object key : clientPropertyKeys) {
 687                             if (key instanceof UIClientPropertyKey) {
 688                                 putClientProperty(key, null);
 689                             }
 690                         }
 691                     }
 692                 }
 693             }
 694         }
 695     }
 696 
 697     /**
 698      * Returns the <code>UIDefaults</code> key used to
 699      * look up the name of the <code>swing.plaf.ComponentUI</code>
 700      * class that defines the look and feel
 701      * for this component.  Most applications will never need to
 702      * call this method.  Subclasses of <code>JComponent</code> that support
 703      * pluggable look and feel should override this method to
 704      * return a <code>UIDefaults</code> key that maps to the
 705      * <code>ComponentUI</code> subclass that defines their look and feel.
 706      *
 707      * @return the <code>UIDefaults</code> key for a
 708      *          <code>ComponentUI</code> subclass
 709      * @see UIDefaults#getUI
 710      * @beaninfo
 711      *      expert: true
 712      * description: UIClassID
 713      */
 714     public String getUIClassID() {
 715         return uiClassID;
 716     }
 717 
 718 
 719     /**
 720      * Returns the graphics object used to paint this component.
 721      * If <code>DebugGraphics</code> is turned on we create a new
 722      * <code>DebugGraphics</code> object if necessary.
 723      * Otherwise we just configure the
 724      * specified graphics object's foreground and font.
 725      *
 726      * @param g the original <code>Graphics</code> object
 727      * @return a <code>Graphics</code> object configured for this component
 728      */
 729     protected Graphics getComponentGraphics(Graphics g) {
 730         Graphics componentGraphics = g;
 731         if (ui != null && DEBUG_GRAPHICS_LOADED) {
 732             if ((DebugGraphics.debugComponentCount() != 0) &&
 733                     (shouldDebugGraphics() != 0) &&
 734                     !(g instanceof DebugGraphics)) {
 735                 componentGraphics = new DebugGraphics(g,this);
 736             }
 737         }
 738         componentGraphics.setColor(getForeground());
 739         componentGraphics.setFont(getFont());
 740 
 741         return componentGraphics;
 742     }
 743 
 744 
 745     /**
 746      * Calls the UI delegate's paint method, if the UI delegate
 747      * is non-<code>null</code>.  We pass the delegate a copy of the
 748      * <code>Graphics</code> object to protect the rest of the
 749      * paint code from irrevocable changes
 750      * (for example, <code>Graphics.translate</code>).
 751      * <p>
 752      * If you override this in a subclass you should not make permanent
 753      * changes to the passed in <code>Graphics</code>. For example, you
 754      * should not alter the clip <code>Rectangle</code> or modify the
 755      * transform. If you need to do these operations you may find it
 756      * easier to create a new <code>Graphics</code> from the passed in
 757      * <code>Graphics</code> and manipulate it. Further, if you do not
 758      * invoker super's implementation you must honor the opaque property,
 759      * that is
 760      * if this component is opaque, you must completely fill in the background
 761      * in a non-opaque color. If you do not honor the opaque property you
 762      * will likely see visual artifacts.
 763      * <p>
 764      * The passed in <code>Graphics</code> object might
 765      * have a transform other than the identify transform
 766      * installed on it.  In this case, you might get
 767      * unexpected results if you cumulatively apply
 768      * another transform.
 769      *
 770      * @param g the <code>Graphics</code> object to protect
 771      * @see #paint
 772      * @see ComponentUI
 773      */
 774     protected void paintComponent(Graphics g) {
 775         if (ui != null) {
 776             Graphics scratchGraphics = (g == null) ? null : g.create();
 777             try {
 778                 ui.update(scratchGraphics, this);
 779             }
 780             finally {
 781                 scratchGraphics.dispose();
 782             }
 783         }
 784     }
 785 
 786     /**
 787      * Paints this component's children.
 788      * If <code>shouldUseBuffer</code> is true,
 789      * no component ancestor has a buffer and
 790      * the component children can use a buffer if they have one.
 791      * Otherwise, one ancestor has a buffer currently in use and children
 792      * should not use a buffer to paint.
 793      * @param g  the <code>Graphics</code> context in which to paint
 794      * @see #paint
 795      * @see java.awt.Container#paint
 796      */
 797     protected void paintChildren(Graphics g) {
 798         Graphics sg = g;
 799 
 800         synchronized(getTreeLock()) {
 801             int i = getComponentCount() - 1;
 802             if (i < 0) {
 803                 return;
 804             }
 805             // If we are only to paint to a specific child, determine
 806             // its index.
 807             if (paintingChild != null &&
 808                 (paintingChild instanceof JComponent) &&
 809                 paintingChild.isOpaque()) {
 810                 for (; i >= 0; i--) {
 811                     if (getComponent(i) == paintingChild){
 812                         break;
 813                     }
 814                 }
 815             }
 816             Rectangle tmpRect = fetchRectangle();
 817             boolean checkSiblings = (!isOptimizedDrawingEnabled() &&
 818                                      checkIfChildObscuredBySibling());
 819             Rectangle clipBounds = null;
 820             if (checkSiblings) {
 821                 clipBounds = sg.getClipBounds();
 822                 if (clipBounds == null) {
 823                     clipBounds = new Rectangle(0, 0, getWidth(),
 824                                                getHeight());
 825                 }
 826             }
 827             boolean printing = getFlag(IS_PRINTING);
 828             final Window window = SwingUtilities.getWindowAncestor(this);
 829             final boolean isWindowOpaque = window == null || window.isOpaque();
 830             for (; i >= 0 ; i--) {
 831                 Component comp = getComponent(i);
 832                 if (comp == null) {
 833                     continue;
 834                 }
 835 
 836                 final boolean isJComponent = comp instanceof JComponent;
 837 
 838                 // Enable painting of heavyweights in non-opaque windows.
 839                 // See 6884960
 840                 if ((!isWindowOpaque || isJComponent ||
 841                             isLightweightComponent(comp)) && comp.isVisible())
 842                 {
 843                     Rectangle cr;
 844 
 845                     cr = comp.getBounds(tmpRect);
 846 
 847                     boolean hitClip = g.hitClip(cr.x, cr.y, cr.width,
 848                                                 cr.height);
 849 
 850                     if (hitClip) {
 851                         if (checkSiblings && i > 0) {
 852                             int x = cr.x;
 853                             int y = cr.y;
 854                             int width = cr.width;
 855                             int height = cr.height;
 856                             SwingUtilities.computeIntersection
 857                                 (clipBounds.x, clipBounds.y,
 858                                  clipBounds.width, clipBounds.height, cr);
 859 
 860                             if(getObscuredState(i, cr.x, cr.y, cr.width,
 861                                           cr.height) == COMPLETELY_OBSCURED) {
 862                                 continue;
 863                             }
 864                             cr.x = x;
 865                             cr.y = y;
 866                             cr.width = width;
 867                             cr.height = height;
 868                         }
 869                         Graphics cg = sg.create(cr.x, cr.y, cr.width,
 870                                                 cr.height);
 871                         cg.setColor(comp.getForeground());
 872                         cg.setFont(comp.getFont());
 873                         boolean shouldSetFlagBack = false;
 874                         try {
 875                             if(isJComponent) {
 876                                 if(getFlag(ANCESTOR_USING_BUFFER)) {
 877                                     ((JComponent)comp).setFlag(
 878                                                  ANCESTOR_USING_BUFFER,true);
 879                                     shouldSetFlagBack = true;
 880                                 }
 881                                 if(getFlag(IS_PAINTING_TILE)) {
 882                                     ((JComponent)comp).setFlag(
 883                                                  IS_PAINTING_TILE,true);
 884                                     shouldSetFlagBack = true;
 885                                 }
 886                                 if(!printing) {
 887                                     comp.paint(cg);
 888                                 }
 889                                 else {
 890                                     if (!getFlag(IS_PRINTING_ALL)) {
 891                                         comp.print(cg);
 892                                     }
 893                                     else {
 894                                         comp.printAll(cg);
 895                                     }
 896                                 }
 897                             } else {
 898                                 // The component is either lightweight, or
 899                                 // heavyweight in a non-opaque window
 900                                 if (!printing) {
 901                                     comp.paint(cg);
 902                                 }
 903                                 else {
 904                                     if (!getFlag(IS_PRINTING_ALL)) {
 905                                         comp.print(cg);
 906                                     }
 907                                     else {
 908                                         comp.printAll(cg);
 909                                     }
 910                                 }
 911                             }
 912                         } finally {
 913                             cg.dispose();
 914                             if(shouldSetFlagBack) {
 915                                 ((JComponent)comp).setFlag(
 916                                              ANCESTOR_USING_BUFFER,false);
 917                                 ((JComponent)comp).setFlag(
 918                                              IS_PAINTING_TILE,false);
 919                             }
 920                         }
 921                     }
 922                 }
 923 
 924             }
 925             recycleRectangle(tmpRect);
 926         }
 927     }
 928 
 929     /**
 930      * Paints the component's border.
 931      * <p>
 932      * If you override this in a subclass you should not make permanent
 933      * changes to the passed in <code>Graphics</code>. For example, you
 934      * should not alter the clip <code>Rectangle</code> or modify the
 935      * transform. If you need to do these operations you may find it
 936      * easier to create a new <code>Graphics</code> from the passed in
 937      * <code>Graphics</code> and manipulate it.
 938      *
 939      * @param g  the <code>Graphics</code> context in which to paint
 940      *
 941      * @see #paint
 942      * @see #setBorder
 943      */
 944     protected void paintBorder(Graphics g) {
 945         Border border = getBorder();
 946         if (border != null) {
 947             border.paintBorder(this, g, 0, 0, getWidth(), getHeight());
 948         }
 949     }
 950 
 951 
 952     /**
 953      * Calls <code>paint</code>.  Doesn't clear the background but see
 954      * <code>ComponentUI.update</code>, which is called by
 955      * <code>paintComponent</code>.
 956      *
 957      * @param g the <code>Graphics</code> context in which to paint
 958      * @see #paint
 959      * @see #paintComponent
 960      * @see javax.swing.plaf.ComponentUI
 961      */
 962     public void update(Graphics g) {
 963         paint(g);
 964     }
 965 
 966 
 967     /**
 968      * Invoked by Swing to draw components.
 969      * Applications should not invoke <code>paint</code> directly,
 970      * but should instead use the <code>repaint</code> method to
 971      * schedule the component for redrawing.
 972      * <p>
 973      * This method actually delegates the work of painting to three
 974      * protected methods: <code>paintComponent</code>,
 975      * <code>paintBorder</code>,
 976      * and <code>paintChildren</code>.  They're called in the order
 977      * listed to ensure that children appear on top of component itself.
 978      * Generally speaking, the component and its children should not
 979      * paint in the insets area allocated to the border. Subclasses can
 980      * just override this method, as always.  A subclass that just
 981      * wants to specialize the UI (look and feel) delegate's
 982      * <code>paint</code> method should just override
 983      * <code>paintComponent</code>.
 984      *
 985      * @param g  the <code>Graphics</code> context in which to paint
 986      * @see #paintComponent
 987      * @see #paintBorder
 988      * @see #paintChildren
 989      * @see #getComponentGraphics
 990      * @see #repaint
 991      */
 992     public void paint(Graphics g) {
 993         boolean shouldClearPaintFlags = false;
 994 
 995         if ((getWidth() <= 0) || (getHeight() <= 0)) {
 996             return;
 997         }
 998 
 999         Graphics componentGraphics = getComponentGraphics(g);
1000         Graphics co = componentGraphics.create();
1001         try {
1002             RepaintManager repaintManager = RepaintManager.currentManager(this);
1003             Rectangle clipRect = co.getClipBounds();
1004             int clipX;
1005             int clipY;
1006             int clipW;
1007             int clipH;
1008             if (clipRect == null) {
1009                 clipX = clipY = 0;
1010                 clipW = getWidth();
1011                 clipH = getHeight();
1012             }
1013             else {
1014                 clipX = clipRect.x;
1015                 clipY = clipRect.y;
1016                 clipW = clipRect.width;
1017                 clipH = clipRect.height;
1018             }
1019 
1020             if(clipW > getWidth()) {
1021                 clipW = getWidth();
1022             }
1023             if(clipH > getHeight()) {
1024                 clipH = getHeight();
1025             }
1026 
1027             if(getParent() != null && !(getParent() instanceof JComponent)) {
1028                 adjustPaintFlags();
1029                 shouldClearPaintFlags = true;
1030             }
1031 
1032             int bw,bh;
1033             boolean printing = getFlag(IS_PRINTING);
1034             if (!printing && repaintManager.isDoubleBufferingEnabled() &&
1035                 !getFlag(ANCESTOR_USING_BUFFER) && isDoubleBuffered() &&
1036                 (getFlag(IS_REPAINTING) || repaintManager.isPainting()))
1037             {
1038                 repaintManager.beginPaint();
1039                 try {
1040                     repaintManager.paint(this, this, co, clipX, clipY, clipW,
1041                                          clipH);
1042                 } finally {
1043                     repaintManager.endPaint();
1044                 }
1045             }
1046             else {
1047                 // Will ocassionaly happen in 1.2, especially when printing.
1048                 if (clipRect == null) {
1049                     co.setClip(clipX, clipY, clipW, clipH);
1050                 }
1051 
1052                 if (!rectangleIsObscured(clipX,clipY,clipW,clipH)) {
1053                     if (!printing) {
1054                         paintComponent(co);
1055                         paintBorder(co);
1056                     }
1057                     else {
1058                         printComponent(co);
1059                         printBorder(co);
1060                     }
1061                 }
1062                 if (!printing) {
1063                     paintChildren(co);
1064                 }
1065                 else {
1066                     printChildren(co);
1067                 }
1068             }
1069         } finally {
1070             co.dispose();
1071             if(shouldClearPaintFlags) {
1072                 setFlag(ANCESTOR_USING_BUFFER,false);
1073                 setFlag(IS_PAINTING_TILE,false);
1074                 setFlag(IS_PRINTING,false);
1075                 setFlag(IS_PRINTING_ALL,false);
1076             }
1077         }
1078     }
1079 
1080     // paint forcing use of the double buffer.  This is used for historical
1081     // reasons: JViewport, when scrolling, previously directly invoked paint
1082     // while turning off double buffering at the RepaintManager level, this
1083     // codes simulates that.
1084     void paintForceDoubleBuffered(Graphics g) {
1085         RepaintManager rm = RepaintManager.currentManager(this);
1086         Rectangle clip = g.getClipBounds();
1087         rm.beginPaint();
1088         setFlag(IS_REPAINTING, true);
1089         try {
1090             rm.paint(this, this, g, clip.x, clip.y, clip.width, clip.height);
1091         } finally {
1092             rm.endPaint();
1093             setFlag(IS_REPAINTING, false);
1094         }
1095     }
1096 
1097     /**
1098      * Returns true if this component, or any of its ancestors, are in
1099      * the processing of painting.
1100      */
1101     boolean isPainting() {
1102         Container component = this;
1103         while (component != null) {
1104             if (component instanceof JComponent &&
1105                    ((JComponent)component).getFlag(ANCESTOR_USING_BUFFER)) {
1106                 return true;
1107             }
1108             component = component.getParent();
1109         }
1110         return false;
1111     }
1112 
1113     private void adjustPaintFlags() {
1114         JComponent jparent;
1115         Container parent;
1116         for(parent = getParent() ; parent != null ; parent =
1117             parent.getParent()) {
1118             if(parent instanceof JComponent) {
1119                 jparent = (JComponent) parent;
1120                 if(jparent.getFlag(ANCESTOR_USING_BUFFER))
1121                   setFlag(ANCESTOR_USING_BUFFER, true);
1122                 if(jparent.getFlag(IS_PAINTING_TILE))
1123                   setFlag(IS_PAINTING_TILE, true);
1124                 if(jparent.getFlag(IS_PRINTING))
1125                   setFlag(IS_PRINTING, true);
1126                 if(jparent.getFlag(IS_PRINTING_ALL))
1127                   setFlag(IS_PRINTING_ALL, true);
1128                 break;
1129             }
1130         }
1131     }
1132 
1133     /**
1134      * Invoke this method to print the component. This method invokes
1135      * <code>print</code> on the component.
1136      *
1137      * @param g the <code>Graphics</code> context in which to paint
1138      * @see #print
1139      * @see #printComponent
1140      * @see #printBorder
1141      * @see #printChildren
1142      */
1143     public void printAll(Graphics g) {
1144         setFlag(IS_PRINTING_ALL, true);
1145         try {
1146             print(g);
1147         }
1148         finally {
1149             setFlag(IS_PRINTING_ALL, false);
1150         }
1151     }
1152 
1153     /**
1154      * Invoke this method to print the component to the specified
1155      * <code>Graphics</code>. This method will result in invocations
1156      * of <code>printComponent</code>, <code>printBorder</code> and
1157      * <code>printChildren</code>. It is recommended that you override
1158      * one of the previously mentioned methods rather than this one if
1159      * your intention is to customize the way printing looks. However,
1160      * it can be useful to override this method should you want to prepare
1161      * state before invoking the superclass behavior. As an example,
1162      * if you wanted to change the component's background color before
1163      * printing, you could do the following:
1164      * <pre>
1165      *     public void print(Graphics g) {
1166      *         Color orig = getBackground();
1167      *         setBackground(Color.WHITE);
1168      *
1169      *         // wrap in try/finally so that we always restore the state
1170      *         try {
1171      *             super.print(g);
1172      *         } finally {
1173      *             setBackground(orig);
1174      *         }
1175      *     }
1176      * </pre>
1177      * <p>
1178      * Alternatively, or for components that delegate painting to other objects,
1179      * you can query during painting whether or not the component is in the
1180      * midst of a print operation. The <code>isPaintingForPrint</code> method provides
1181      * this ability and its return value will be changed by this method: to
1182      * <code>true</code> immediately before rendering and to <code>false</code>
1183      * immediately after. With each change a property change event is fired on
1184      * this component with the name <code>"paintingForPrint"</code>.
1185      * <p>
1186      * This method sets the component's state such that the double buffer
1187      * will not be used: painting will be done directly on the passed in
1188      * <code>Graphics</code>.
1189      *
1190      * @param g the <code>Graphics</code> context in which to paint
1191      * @see #printComponent
1192      * @see #printBorder
1193      * @see #printChildren
1194      * @see #isPaintingForPrint
1195      */
1196     public void print(Graphics g) {
1197         setFlag(IS_PRINTING, true);
1198         firePropertyChange("paintingForPrint", false, true);
1199         try {
1200             paint(g);
1201         }
1202         finally {
1203             setFlag(IS_PRINTING, false);
1204             firePropertyChange("paintingForPrint", true, false);
1205         }
1206     }
1207 
1208     /**
1209      * This is invoked during a printing operation. This is implemented to
1210      * invoke <code>paintComponent</code> on the component. Override this
1211      * if you wish to add special painting behavior when printing.
1212      *
1213      * @param g the <code>Graphics</code> context in which to paint
1214      * @see #print
1215      * @since 1.3
1216      */
1217     protected void printComponent(Graphics g) {
1218         paintComponent(g);
1219     }
1220 
1221     /**
1222      * Prints this component's children. This is implemented to invoke
1223      * <code>paintChildren</code> on the component. Override this if you
1224      * wish to print the children differently than painting.
1225      *
1226      * @param g the <code>Graphics</code> context in which to paint
1227      * @see #print
1228      * @since 1.3
1229      */
1230     protected void printChildren(Graphics g) {
1231         paintChildren(g);
1232     }
1233 
1234     /**
1235      * Prints the component's border. This is implemented to invoke
1236      * <code>paintBorder</code> on the component. Override this if you
1237      * wish to print the border differently that it is painted.
1238      *
1239      * @param g the <code>Graphics</code> context in which to paint
1240      * @see #print
1241      * @since 1.3
1242      */
1243     protected void printBorder(Graphics g) {
1244         paintBorder(g);
1245     }
1246 
1247     /**
1248      *  Returns true if the component is currently painting a tile.
1249      *  If this method returns true, paint will be called again for another
1250      *  tile. This method returns false if you are not painting a tile or
1251      *  if the last tile is painted.
1252      *  Use this method to keep some state you might need between tiles.
1253      *
1254      *  @return  true if the component is currently painting a tile,
1255      *          false otherwise
1256      */
1257     public boolean isPaintingTile() {
1258         return getFlag(IS_PAINTING_TILE);
1259     }
1260 
1261     /**
1262      * Returns <code>true</code> if the current painting operation on this
1263      * component is part of a <code>print</code> operation. This method is
1264      * useful when you want to customize what you print versus what you show
1265      * on the screen.
1266      * <p>
1267      * You can detect changes in the value of this property by listening for
1268      * property change events on this component with name
1269      * <code>"paintingForPrint"</code>.
1270      * <p>
1271      * Note: This method provides complimentary functionality to that provided
1272      * by other high level Swing printing APIs. However, it deals strictly with
1273      * painting and should not be confused as providing information on higher
1274      * level print processes. For example, a {@link javax.swing.JTable#print()}
1275      * operation doesn't necessarily result in a continuous rendering of the
1276      * full component, and the return value of this method can change multiple
1277      * times during that operation. It is even possible for the component to be
1278      * painted to the screen while the printing process is ongoing. In such a
1279      * case, the return value of this method is <code>true</code> when, and only
1280      * when, the table is being painted as part of the printing process.
1281      *
1282      * @return true if the current painting operation on this component
1283      *         is part of a print operation
1284      * @see #print
1285      * @since 1.6
1286      */
1287     public final boolean isPaintingForPrint() {
1288         return getFlag(IS_PRINTING);
1289     }
1290 
1291     /**
1292      * In release 1.4, the focus subsystem was rearchitected.
1293      * For more information, see
1294      * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
1295      * How to Use the Focus Subsystem</a>,
1296      * a section in <em>The Java Tutorial</em>.
1297      * <p>
1298      * Changes this <code>JComponent</code>'s focus traversal keys to
1299      * CTRL+TAB and CTRL+SHIFT+TAB. Also prevents
1300      * <code>SortingFocusTraversalPolicy</code> from considering descendants
1301      * of this JComponent when computing a focus traversal cycle.
1302      *
1303      * @see java.awt.Component#setFocusTraversalKeys
1304      * @see SortingFocusTraversalPolicy
1305      * @deprecated As of 1.4, replaced by
1306      *   <code>Component.setFocusTraversalKeys(int, Set)</code> and
1307      *   <code>Container.setFocusCycleRoot(boolean)</code>.
1308      */
1309     @Deprecated
1310     public boolean isManagingFocus() {
1311         return false;
1312     }
1313 
1314     private void registerNextFocusableComponent() {
1315         registerNextFocusableComponent(getNextFocusableComponent());
1316     }
1317 
1318     private void registerNextFocusableComponent(Component
1319                                                 nextFocusableComponent) {
1320         if (nextFocusableComponent == null) {
1321             return;
1322         }
1323 
1324         Container nearestRoot =
1325             (isFocusCycleRoot()) ? this : getFocusCycleRootAncestor();
1326         FocusTraversalPolicy policy = nearestRoot.getFocusTraversalPolicy();
1327         if (!(policy instanceof LegacyGlueFocusTraversalPolicy)) {
1328             policy = new LegacyGlueFocusTraversalPolicy(policy);
1329             nearestRoot.setFocusTraversalPolicy(policy);
1330         }
1331         ((LegacyGlueFocusTraversalPolicy)policy).
1332             setNextFocusableComponent(this, nextFocusableComponent);
1333     }
1334 
1335     private void deregisterNextFocusableComponent() {
1336         Component nextFocusableComponent = getNextFocusableComponent();
1337         if (nextFocusableComponent == null) {
1338             return;
1339         }
1340 
1341         Container nearestRoot =
1342             (isFocusCycleRoot()) ? this : getFocusCycleRootAncestor();
1343         if (nearestRoot == null) {
1344             return;
1345         }
1346         FocusTraversalPolicy policy = nearestRoot.getFocusTraversalPolicy();
1347         if (policy instanceof LegacyGlueFocusTraversalPolicy) {
1348             ((LegacyGlueFocusTraversalPolicy)policy).
1349                 unsetNextFocusableComponent(this, nextFocusableComponent);
1350         }
1351     }
1352 
1353     /**
1354      * In release 1.4, the focus subsystem was rearchitected.
1355      * For more information, see
1356      * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
1357      * How to Use the Focus Subsystem</a>,
1358      * a section in <em>The Java Tutorial</em>.
1359      * <p>
1360      * Overrides the default <code>FocusTraversalPolicy</code> for this
1361      * <code>JComponent</code>'s focus traversal cycle by unconditionally
1362      * setting the specified <code>Component</code> as the next
1363      * <code>Component</code> in the cycle, and this <code>JComponent</code>
1364      * as the specified <code>Component</code>'s previous
1365      * <code>Component</code> in the cycle.
1366      *
1367      * @param aComponent the <code>Component</code> that should follow this
1368      *        <code>JComponent</code> in the focus traversal cycle
1369      *
1370      * @see #getNextFocusableComponent
1371      * @see java.awt.FocusTraversalPolicy
1372      * @deprecated As of 1.4, replaced by <code>FocusTraversalPolicy</code>
1373      */
1374     @Deprecated
1375     public void setNextFocusableComponent(Component aComponent) {
1376         boolean displayable = isDisplayable();
1377         if (displayable) {
1378             deregisterNextFocusableComponent();
1379         }
1380         putClientProperty(NEXT_FOCUS, aComponent);
1381         if (displayable) {
1382             registerNextFocusableComponent(aComponent);
1383         }
1384     }
1385 
1386     /**
1387      * In release 1.4, the focus subsystem was rearchitected.
1388      * For more information, see
1389      * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
1390      * How to Use the Focus Subsystem</a>,
1391      * a section in <em>The Java Tutorial</em>.
1392      * <p>
1393      * Returns the <code>Component</code> set by a prior call to
1394      * <code>setNextFocusableComponent(Component)</code> on this
1395      * <code>JComponent</code>.
1396      *
1397      * @return the <code>Component</code> that will follow this
1398      *        <code>JComponent</code> in the focus traversal cycle, or
1399      *        <code>null</code> if none has been explicitly specified
1400      *
1401      * @see #setNextFocusableComponent
1402      * @deprecated As of 1.4, replaced by <code>FocusTraversalPolicy</code>.
1403      */
1404     @Deprecated
1405     public Component getNextFocusableComponent() {
1406         return (Component)getClientProperty(NEXT_FOCUS);
1407     }
1408 
1409     /**
1410      * Provides a hint as to whether or not this <code>JComponent</code>
1411      * should get focus. This is only a hint, and it is up to consumers that
1412      * are requesting focus to honor this property. This is typically honored
1413      * for mouse operations, but not keyboard operations. For example, look
1414      * and feels could verify this property is true before requesting focus
1415      * during a mouse operation. This would often times be used if you did
1416      * not want a mouse press on a <code>JComponent</code> to steal focus,
1417      * but did want the <code>JComponent</code> to be traversable via the
1418      * keyboard. If you do not want this <code>JComponent</code> focusable at
1419      * all, use the <code>setFocusable</code> method instead.
1420      * <p>
1421      * Please see
1422      * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
1423      * How to Use the Focus Subsystem</a>,
1424      * a section in <em>The Java Tutorial</em>,
1425      * for more information.
1426      *
1427      * @param requestFocusEnabled indicates whether you want this
1428      *        <code>JComponent</code> to be focusable or not
1429      * @see <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
1430      * @see java.awt.Component#setFocusable
1431      */
1432     public void setRequestFocusEnabled(boolean requestFocusEnabled) {
1433         setFlag(REQUEST_FOCUS_DISABLED, !requestFocusEnabled);
1434     }
1435 
1436     /**
1437      * Returns <code>true</code> if this <code>JComponent</code> should
1438      * get focus; otherwise returns <code>false</code>.
1439      * <p>
1440      * Please see
1441      * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
1442      * How to Use the Focus Subsystem</a>,
1443      * a section in <em>The Java Tutorial</em>,
1444      * for more information.
1445      *
1446      * @return <code>true</code> if this component should get focus,
1447      *     otherwise returns <code>false</code>
1448      * @see #setRequestFocusEnabled
1449      * @see <a href="../../java/awt/doc-files/FocusSpec.html">Focus
1450      *      Specification</a>
1451      * @see java.awt.Component#isFocusable
1452      */
1453     public boolean isRequestFocusEnabled() {
1454         return !getFlag(REQUEST_FOCUS_DISABLED);
1455     }
1456 
1457     /**
1458      * Requests that this <code>Component</code> gets the input focus.
1459      * Refer to {@link java.awt.Component#requestFocus()
1460      * Component.requestFocus()} for a complete description of
1461      * this method.
1462      * <p>
1463      * Note that the use of this method is discouraged because
1464      * its behavior is platform dependent. Instead we recommend the
1465      * use of {@link #requestFocusInWindow() requestFocusInWindow()}.
1466      * If you would like more information on focus, see
1467      * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
1468      * How to Use the Focus Subsystem</a>,
1469      * a section in <em>The Java Tutorial</em>.
1470      *
1471      * @see java.awt.Component#requestFocusInWindow()
1472      * @see java.awt.Component#requestFocusInWindow(boolean)
1473      * @since 1.4
1474      */
1475     public void requestFocus() {
1476         super.requestFocus();
1477     }
1478 
1479     /**
1480      * Requests that this <code>Component</code> gets the input focus.
1481      * Refer to {@link java.awt.Component#requestFocus(boolean)
1482      * Component.requestFocus(boolean)} for a complete description of
1483      * this method.
1484      * <p>
1485      * Note that the use of this method is discouraged because
1486      * its behavior is platform dependent. Instead we recommend the
1487      * use of {@link #requestFocusInWindow(boolean)
1488      * requestFocusInWindow(boolean)}.
1489      * If you would like more information on focus, see
1490      * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
1491      * How to Use the Focus Subsystem</a>,
1492      * a section in <em>The Java Tutorial</em>.
1493      *
1494      * @param temporary boolean indicating if the focus change is temporary
1495      * @return <code>false</code> if the focus change request is guaranteed to
1496      *         fail; <code>true</code> if it is likely to succeed
1497      * @see java.awt.Component#requestFocusInWindow()
1498      * @see java.awt.Component#requestFocusInWindow(boolean)
1499      * @since 1.4
1500      */
1501     public boolean requestFocus(boolean temporary) {
1502         return super.requestFocus(temporary);
1503     }
1504 
1505     /**
1506      * Requests that this <code>Component</code> gets the input focus.
1507      * Refer to {@link java.awt.Component#requestFocusInWindow()
1508      * Component.requestFocusInWindow()} for a complete description of
1509      * this method.
1510      * <p>
1511      * If you would like more information on focus, see
1512      * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
1513      * How to Use the Focus Subsystem</a>,
1514      * a section in <em>The Java Tutorial</em>.
1515      *
1516      * @return <code>false</code> if the focus change request is guaranteed to
1517      *         fail; <code>true</code> if it is likely to succeed
1518      * @see java.awt.Component#requestFocusInWindow()
1519      * @see java.awt.Component#requestFocusInWindow(boolean)
1520      * @since 1.4
1521      */
1522     public boolean requestFocusInWindow() {
1523         return super.requestFocusInWindow();
1524     }
1525 
1526     /**
1527      * Requests that this <code>Component</code> gets the input focus.
1528      * Refer to {@link java.awt.Component#requestFocusInWindow(boolean)
1529      * Component.requestFocusInWindow(boolean)} for a complete description of
1530      * this method.
1531      * <p>
1532      * If you would like more information on focus, see
1533      * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
1534      * How to Use the Focus Subsystem</a>,
1535      * a section in <em>The Java Tutorial</em>.
1536      *
1537      * @param temporary boolean indicating if the focus change is temporary
1538      * @return <code>false</code> if the focus change request is guaranteed to
1539      *         fail; <code>true</code> if it is likely to succeed
1540      * @see java.awt.Component#requestFocusInWindow()
1541      * @see java.awt.Component#requestFocusInWindow(boolean)
1542      * @since 1.4
1543      */
1544     protected boolean requestFocusInWindow(boolean temporary) {
1545         return super.requestFocusInWindow(temporary);
1546     }
1547 
1548     /**
1549      * Requests that this Component get the input focus, and that this
1550      * Component's top-level ancestor become the focused Window. This component
1551      * must be displayable, visible, and focusable for the request to be
1552      * granted.
1553      * <p>
1554      * This method is intended for use by focus implementations. Client code
1555      * should not use this method; instead, it should use
1556      * <code>requestFocusInWindow()</code>.
1557      *
1558      * @see #requestFocusInWindow()
1559      */
1560     public void grabFocus() {
1561         requestFocus();
1562     }
1563 
1564     /**
1565      * Sets the value to indicate whether input verifier for the
1566      * current focus owner will be called before this component requests
1567      * focus. The default is true. Set to false on components such as a
1568      * Cancel button or a scrollbar, which should activate even if the
1569      * input in the current focus owner is not "passed" by the input
1570      * verifier for that component.
1571      *
1572      * @param verifyInputWhenFocusTarget value for the
1573      *        <code>verifyInputWhenFocusTarget</code> property
1574      * @see InputVerifier
1575      * @see #setInputVerifier
1576      * @see #getInputVerifier
1577      * @see #getVerifyInputWhenFocusTarget
1578      *
1579      * @since 1.3
1580      * @beaninfo
1581      *       bound: true
1582      * description: Whether the Component verifies input before accepting
1583      *              focus.
1584      */
1585     public void setVerifyInputWhenFocusTarget(boolean
1586                                               verifyInputWhenFocusTarget) {
1587         boolean oldVerifyInputWhenFocusTarget =
1588             this.verifyInputWhenFocusTarget;
1589         this.verifyInputWhenFocusTarget = verifyInputWhenFocusTarget;
1590         firePropertyChange("verifyInputWhenFocusTarget",
1591                            oldVerifyInputWhenFocusTarget,
1592                            verifyInputWhenFocusTarget);
1593     }
1594 
1595     /**
1596      * Returns the value that indicates whether the input verifier for the
1597      * current focus owner will be called before this component requests
1598      * focus.
1599      *
1600      * @return value of the <code>verifyInputWhenFocusTarget</code> property
1601      *
1602      * @see InputVerifier
1603      * @see #setInputVerifier
1604      * @see #getInputVerifier
1605      * @see #setVerifyInputWhenFocusTarget
1606      *
1607      * @since 1.3
1608      */
1609     public boolean getVerifyInputWhenFocusTarget() {
1610         return verifyInputWhenFocusTarget;
1611     }
1612 
1613 
1614     /**
1615      * Gets the <code>FontMetrics</code> for the specified <code>Font</code>.
1616      *
1617      * @param font the font for which font metrics is to be
1618      *          obtained
1619      * @return the font metrics for <code>font</code>
1620      * @throws NullPointerException if <code>font</code> is null
1621      * @since 1.5
1622      */
1623     public FontMetrics getFontMetrics(Font font) {
1624         return SwingUtilities2.getFontMetrics(this, font);
1625     }
1626 
1627 
1628     /**
1629      * Sets the preferred size of this component.
1630      * If <code>preferredSize</code> is <code>null</code>, the UI will
1631      * be asked for the preferred size.
1632      * @beaninfo
1633      *   preferred: true
1634      *       bound: true
1635      * description: The preferred size of the component.
1636      */
1637     public void setPreferredSize(Dimension preferredSize) {
1638         super.setPreferredSize(preferredSize);
1639     }
1640 
1641 
1642     /**
1643      * If the <code>preferredSize</code> has been set to a
1644      * non-<code>null</code> value just returns it.
1645      * If the UI delegate's <code>getPreferredSize</code>
1646      * method returns a non <code>null</code> value then return that;
1647      * otherwise defer to the component's layout manager.
1648      *
1649      * @return the value of the <code>preferredSize</code> property
1650      * @see #setPreferredSize
1651      * @see ComponentUI
1652      */
1653     @Transient
1654     public Dimension getPreferredSize() {
1655         if (isPreferredSizeSet()) {
1656             return super.getPreferredSize();
1657         }
1658         Dimension size = null;
1659         if (ui != null) {
1660             size = ui.getPreferredSize(this);
1661         }
1662         return (size != null) ? size : super.getPreferredSize();
1663     }
1664 
1665 
1666     /**
1667      * Sets the maximum size of this component to a constant
1668      * value.  Subsequent calls to <code>getMaximumSize</code> will always
1669      * return this value; the component's UI will not be asked
1670      * to compute it.  Setting the maximum size to <code>null</code>
1671      * restores the default behavior.
1672      *
1673      * @param maximumSize a <code>Dimension</code> containing the
1674      *          desired maximum allowable size
1675      * @see #getMaximumSize
1676      * @beaninfo
1677      *       bound: true
1678      * description: The maximum size of the component.
1679      */
1680     public void setMaximumSize(Dimension maximumSize) {
1681         super.setMaximumSize(maximumSize);
1682     }
1683 
1684 
1685     /**
1686      * If the maximum size has been set to a non-<code>null</code> value
1687      * just returns it.  If the UI delegate's <code>getMaximumSize</code>
1688      * method returns a non-<code>null</code> value then return that;
1689      * otherwise defer to the component's layout manager.
1690      *
1691      * @return the value of the <code>maximumSize</code> property
1692      * @see #setMaximumSize
1693      * @see ComponentUI
1694      */
1695     @Transient
1696     public Dimension getMaximumSize() {
1697         if (isMaximumSizeSet()) {
1698             return super.getMaximumSize();
1699         }
1700         Dimension size = null;
1701         if (ui != null) {
1702             size = ui.getMaximumSize(this);
1703         }
1704         return (size != null) ? size : super.getMaximumSize();
1705     }
1706 
1707 
1708     /**
1709      * Sets the minimum size of this component to a constant
1710      * value.  Subsequent calls to <code>getMinimumSize</code> will always
1711      * return this value; the component's UI will not be asked
1712      * to compute it.  Setting the minimum size to <code>null</code>
1713      * restores the default behavior.
1714      *
1715      * @param minimumSize the new minimum size of this component
1716      * @see #getMinimumSize
1717      * @beaninfo
1718      *       bound: true
1719      * description: The minimum size of the component.
1720      */
1721     public void setMinimumSize(Dimension minimumSize) {
1722         super.setMinimumSize(minimumSize);
1723     }
1724 
1725     /**
1726      * If the minimum size has been set to a non-<code>null</code> value
1727      * just returns it.  If the UI delegate's <code>getMinimumSize</code>
1728      * method returns a non-<code>null</code> value then return that; otherwise
1729      * defer to the component's layout manager.
1730      *
1731      * @return the value of the <code>minimumSize</code> property
1732      * @see #setMinimumSize
1733      * @see ComponentUI
1734      */
1735     @Transient
1736     public Dimension getMinimumSize() {
1737         if (isMinimumSizeSet()) {
1738             return super.getMinimumSize();
1739         }
1740         Dimension size = null;
1741         if (ui != null) {
1742             size = ui.getMinimumSize(this);
1743         }
1744         return (size != null) ? size : super.getMinimumSize();
1745     }
1746 
1747     /**
1748      * Gives the UI delegate an opportunity to define the precise
1749      * shape of this component for the sake of mouse processing.
1750      *
1751      * @return true if this component logically contains x,y
1752      * @see java.awt.Component#contains(int, int)
1753      * @see ComponentUI
1754      */
1755     public boolean contains(int x, int y) {
1756         return (ui != null) ? ui.contains(this, x, y) : super.contains(x, y);
1757     }
1758 
1759     /**
1760      * Sets the border of this component.  The <code>Border</code> object is
1761      * responsible for defining the insets for the component
1762      * (overriding any insets set directly on the component) and
1763      * for optionally rendering any border decorations within the
1764      * bounds of those insets.  Borders should be used (rather
1765      * than insets) for creating both decorative and non-decorative
1766      * (such as margins and padding) regions for a swing component.
1767      * Compound borders can be used to nest multiple borders within a
1768      * single component.
1769      * <p>
1770      * Although technically you can set the border on any object
1771      * that inherits from <code>JComponent</code>, the look and
1772      * feel implementation of many standard Swing components
1773      * doesn't work well with user-set borders.  In general,
1774      * when you want to set a border on a standard Swing
1775      * component other than <code>JPanel</code> or <code>JLabel</code>,
1776      * we recommend that you put the component in a <code>JPanel</code>
1777      * and set the border on the <code>JPanel</code>.
1778      * <p>
1779      * This is a bound property.
1780      *
1781      * @param border the border to be rendered for this component
1782      * @see Border
1783      * @see CompoundBorder
1784      * @beaninfo
1785      *        bound: true
1786      *    preferred: true
1787      *    attribute: visualUpdate true
1788      *  description: The component's border.
1789      */
1790     public void setBorder(Border border) {
1791         Border         oldBorder = this.border;
1792 
1793         this.border = border;
1794         firePropertyChange("border", oldBorder, border);
1795         if (border != oldBorder) {
1796             if (border == null || oldBorder == null ||
1797                 !(border.getBorderInsets(this).equals(oldBorder.getBorderInsets(this)))) {
1798                 revalidate();
1799             }
1800             repaint();
1801         }
1802     }
1803 
1804     /**
1805      * Returns the border of this component or <code>null</code> if no
1806      * border is currently set.
1807      *
1808      * @return the border object for this component
1809      * @see #setBorder
1810      */
1811     public Border getBorder() {
1812         return border;
1813     }
1814 
1815     /**
1816      * If a border has been set on this component, returns the
1817      * border's insets; otherwise calls <code>super.getInsets</code>.
1818      *
1819      * @return the value of the insets property
1820      * @see #setBorder
1821      */
1822     public Insets getInsets() {
1823         if (border != null) {
1824             return border.getBorderInsets(this);
1825         }
1826         return super.getInsets();
1827     }
1828 
1829     /**
1830      * Returns an <code>Insets</code> object containing this component's inset
1831      * values.  The passed-in <code>Insets</code> object will be reused
1832      * if possible.
1833      * Calling methods cannot assume that the same object will be returned,
1834      * however.  All existing values within this object are overwritten.
1835      * If <code>insets</code> is null, this will allocate a new one.
1836      *
1837      * @param insets the <code>Insets</code> object, which can be reused
1838      * @return the <code>Insets</code> object
1839      * @see #getInsets
1840      * @beaninfo
1841      *   expert: true
1842      */
1843     public Insets getInsets(Insets insets) {
1844         if (insets == null) {
1845             insets = new Insets(0, 0, 0, 0);
1846         }
1847         if (border != null) {
1848             if (border instanceof AbstractBorder) {
1849                 return ((AbstractBorder)border).getBorderInsets(this, insets);
1850             } else {
1851                 // Can't reuse border insets because the Border interface
1852                 // can't be enhanced.
1853                 return border.getBorderInsets(this);
1854             }
1855         } else {
1856             // super.getInsets() always returns an Insets object with
1857             // all of its value zeroed.  No need for a new object here.
1858             insets.left = insets.top = insets.right = insets.bottom = 0;
1859             return insets;
1860         }
1861     }
1862 
1863     /**
1864      * Overrides <code>Container.getAlignmentY</code> to return
1865      * the horizontal alignment.
1866      *
1867      * @return the value of the <code>alignmentY</code> property
1868      * @see #setAlignmentY
1869      * @see java.awt.Component#getAlignmentY
1870      */
1871     public float getAlignmentY() {
1872         if (isAlignmentYSet) {
1873             return alignmentY;
1874         }
1875         return super.getAlignmentY();
1876     }
1877 
1878     /**
1879      * Sets the the horizontal alignment.
1880      *
1881      * @param alignmentY  the new horizontal alignment
1882      * @see #getAlignmentY
1883      * @beaninfo
1884      *   description: The preferred vertical alignment of the component.
1885      */
1886     public void setAlignmentY(float alignmentY) {
1887         this.alignmentY = alignmentY > 1.0f ? 1.0f : alignmentY < 0.0f ? 0.0f : alignmentY;
1888         isAlignmentYSet = true;
1889     }
1890 
1891 
1892     /**
1893      * Overrides <code>Container.getAlignmentX</code> to return
1894      * the vertical alignment.
1895      *
1896      * @return the value of the <code>alignmentX</code> property
1897      * @see #setAlignmentX
1898      * @see java.awt.Component#getAlignmentX
1899      */
1900     public float getAlignmentX() {
1901         if (isAlignmentXSet) {
1902             return alignmentX;
1903         }
1904         return super.getAlignmentX();
1905     }
1906 
1907     /**
1908      * Sets the the vertical alignment.
1909      *
1910      * @param alignmentX  the new vertical alignment
1911      * @see #getAlignmentX
1912      * @beaninfo
1913      *   description: The preferred horizontal alignment of the component.
1914      */
1915     public void setAlignmentX(float alignmentX) {
1916         this.alignmentX = alignmentX > 1.0f ? 1.0f : alignmentX < 0.0f ? 0.0f : alignmentX;
1917         isAlignmentXSet = true;
1918     }
1919 
1920     /**
1921      * Sets the input verifier for this component.
1922      *
1923      * @param inputVerifier the new input verifier
1924      * @since 1.3
1925      * @see InputVerifier
1926      * @beaninfo
1927      *       bound: true
1928      * description: The component's input verifier.
1929      */
1930     public void setInputVerifier(InputVerifier inputVerifier) {
1931         InputVerifier oldInputVerifier = (InputVerifier)getClientProperty(
1932                                          JComponent_INPUT_VERIFIER);
1933         putClientProperty(JComponent_INPUT_VERIFIER, inputVerifier);
1934         firePropertyChange("inputVerifier", oldInputVerifier, inputVerifier);
1935     }
1936 
1937     /**
1938      * Returns the input verifier for this component.
1939      *
1940      * @return the <code>inputVerifier</code> property
1941      * @since 1.3
1942      * @see InputVerifier
1943      */
1944     public InputVerifier getInputVerifier() {
1945         return (InputVerifier)getClientProperty(JComponent_INPUT_VERIFIER);
1946     }
1947 
1948     /**
1949      * Returns this component's graphics context, which lets you draw
1950      * on a component. Use this method to get a <code>Graphics</code> object and
1951      * then invoke operations on that object to draw on the component.
1952      * @return this components graphics context
1953      */
1954     public Graphics getGraphics() {
1955         if (DEBUG_GRAPHICS_LOADED && shouldDebugGraphics() != 0) {
1956             DebugGraphics graphics = new DebugGraphics(super.getGraphics(),
1957                                                        this);
1958             return graphics;
1959         }
1960         return super.getGraphics();
1961     }
1962 
1963 
1964     /** Enables or disables diagnostic information about every graphics
1965       * operation performed within the component or one of its children.
1966       *
1967       * @param debugOptions  determines how the component should display
1968       *         the information;  one of the following options:
1969       * <ul>
1970       * <li>DebugGraphics.LOG_OPTION - causes a text message to be printed.
1971       * <li>DebugGraphics.FLASH_OPTION - causes the drawing to flash several
1972       * times.
1973       * <li>DebugGraphics.BUFFERED_OPTION - creates an
1974       *         <code>ExternalWindow</code> that displays the operations
1975       *         performed on the View's offscreen buffer.
1976       * <li>DebugGraphics.NONE_OPTION disables debugging.
1977       * <li>A value of 0 causes no changes to the debugging options.
1978       * </ul>
1979       * <code>debugOptions</code> is bitwise OR'd into the current value
1980       *
1981       * @beaninfo
1982       *   preferred: true
1983       *        enum: NONE_OPTION DebugGraphics.NONE_OPTION
1984       *              LOG_OPTION DebugGraphics.LOG_OPTION
1985       *              FLASH_OPTION DebugGraphics.FLASH_OPTION
1986       *              BUFFERED_OPTION DebugGraphics.BUFFERED_OPTION
1987       * description: Diagnostic options for graphics operations.
1988       */
1989     public void setDebugGraphicsOptions(int debugOptions) {
1990         DebugGraphics.setDebugOptions(this, debugOptions);
1991     }
1992 
1993     /** Returns the state of graphics debugging.
1994       *
1995       * @return a bitwise OR'd flag of zero or more of the following options:
1996       * <ul>
1997       * <li>DebugGraphics.LOG_OPTION - causes a text message to be printed.
1998       * <li>DebugGraphics.FLASH_OPTION - causes the drawing to flash several
1999       * times.
2000       * <li>DebugGraphics.BUFFERED_OPTION - creates an
2001       *         <code>ExternalWindow</code> that displays the operations
2002       *         performed on the View's offscreen buffer.
2003       * <li>DebugGraphics.NONE_OPTION disables debugging.
2004       * <li>A value of 0 causes no changes to the debugging options.
2005       * </ul>
2006       * @see #setDebugGraphicsOptions
2007       */
2008     public int getDebugGraphicsOptions() {
2009         return DebugGraphics.getDebugOptions(this);
2010     }
2011 
2012 
2013     /**
2014      * Returns true if debug information is enabled for this
2015      * <code>JComponent</code> or one of its parents.
2016      */
2017     int shouldDebugGraphics() {
2018         return DebugGraphics.shouldComponentDebug(this);
2019     }
2020 
2021     /**
2022      * This method is now obsolete, please use a combination of
2023      * <code>getActionMap()</code> and <code>getInputMap()</code> for
2024      * similar behavior. For example, to bind the <code>KeyStroke</code>
2025      * <code>aKeyStroke</code> to the <code>Action</code> <code>anAction</code>
2026      * now use:
2027      * <pre>
2028      *   component.getInputMap().put(aKeyStroke, aCommand);
2029      *   component.getActionMap().put(aCommmand, anAction);
2030      * </pre>
2031      * The above assumes you want the binding to be applicable for
2032      * <code>WHEN_FOCUSED</code>. To register bindings for other focus
2033      * states use the <code>getInputMap</code> method that takes an integer.
2034      * <p>
2035      * Register a new keyboard action.
2036      * <code>anAction</code> will be invoked if a key event matching
2037      * <code>aKeyStroke</code> occurs and <code>aCondition</code> is verified.
2038      * The <code>KeyStroke</code> object defines a
2039      * particular combination of a keyboard key and one or more modifiers
2040      * (alt, shift, ctrl, meta).
2041      * <p>
2042      * The <code>aCommand</code> will be set in the delivered event if
2043      * specified.
2044      * <p>
2045      * The <code>aCondition</code> can be one of:
2046      * <blockquote>
2047      * <DL>
2048      * <DT>WHEN_FOCUSED
2049      * <DD>The action will be invoked only when the keystroke occurs
2050      *     while the component has the focus.
2051      * <DT>WHEN_IN_FOCUSED_WINDOW
2052      * <DD>The action will be invoked when the keystroke occurs while
2053      *     the component has the focus or if the component is in the
2054      *     window that has the focus. Note that the component need not
2055      *     be an immediate descendent of the window -- it can be
2056      *     anywhere in the window's containment hierarchy. In other
2057      *     words, whenever <em>any</em> component in the window has the focus,
2058      *     the action registered with this component is invoked.
2059      * <DT>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
2060      * <DD>The action will be invoked when the keystroke occurs while the
2061      *     component has the focus or if the component is an ancestor of
2062      *     the component that has the focus.
2063      * </DL>
2064      * </blockquote>
2065      * <p>
2066      * The combination of keystrokes and conditions lets you define high
2067      * level (semantic) action events for a specified keystroke+modifier
2068      * combination (using the KeyStroke class) and direct to a parent or
2069      * child of a component that has the focus, or to the component itself.
2070      * In other words, in any hierarchical structure of components, an
2071      * arbitrary key-combination can be immediately directed to the
2072      * appropriate component in the hierarchy, and cause a specific method
2073      * to be invoked (usually by way of adapter objects).
2074      * <p>
2075      * If an action has already been registered for the receiving
2076      * container, with the same charCode and the same modifiers,
2077      * <code>anAction</code> will replace the action.
2078      *
2079      * @param anAction  the <code>Action</code> to be registered
2080      * @param aCommand  the command to be set in the delivered event
2081      * @param aKeyStroke the <code>KeyStroke</code> to bind to the action
2082      * @param aCondition the condition that needs to be met, see above
2083      * @see KeyStroke
2084      */
2085     public void registerKeyboardAction(ActionListener anAction,String aCommand,KeyStroke aKeyStroke,int aCondition) {
2086 
2087         InputMap inputMap = getInputMap(aCondition, true);
2088 
2089         if (inputMap != null) {
2090             ActionMap actionMap = getActionMap(true);
2091             ActionStandin action = new ActionStandin(anAction, aCommand);
2092             inputMap.put(aKeyStroke, action);
2093             if (actionMap != null) {
2094                 actionMap.put(action, action);
2095             }
2096         }
2097     }
2098 
2099     /**
2100      * Registers any bound <code>WHEN_IN_FOCUSED_WINDOW</code> actions with
2101      * the <code>KeyboardManager</code>. If <code>onlyIfNew</code>
2102      * is true only actions that haven't been registered are pushed
2103      * to the <code>KeyboardManager</code>;
2104      * otherwise all actions are pushed to the <code>KeyboardManager</code>.
2105      *
2106      * @param onlyIfNew  if true, only actions that haven't been registered
2107      *          are pushed to the <code>KeyboardManager</code>
2108      */
2109     private void registerWithKeyboardManager(boolean onlyIfNew) {
2110         InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW, false);
2111         KeyStroke[] strokes;
2112         Hashtable<KeyStroke, KeyStroke> registered =
2113                 (Hashtable<KeyStroke, KeyStroke>)getClientProperty
2114                                 (WHEN_IN_FOCUSED_WINDOW_BINDINGS);
2115 
2116         if (inputMap != null) {
2117             // Push any new KeyStrokes to the KeyboardManager.
2118             strokes = inputMap.allKeys();
2119             if (strokes != null) {
2120                 for (int counter = strokes.length - 1; counter >= 0;
2121                      counter--) {
2122                     if (!onlyIfNew || registered == null ||
2123                         registered.get(strokes[counter]) == null) {
2124                         registerWithKeyboardManager(strokes[counter]);
2125                     }
2126                     if (registered != null) {
2127                         registered.remove(strokes[counter]);
2128                     }
2129                 }
2130             }
2131         }
2132         else {
2133             strokes = null;
2134         }
2135         // Remove any old ones.
2136         if (registered != null && registered.size() > 0) {
2137             Enumeration<KeyStroke> keys = registered.keys();
2138 
2139             while (keys.hasMoreElements()) {
2140                 KeyStroke ks = keys.nextElement();
2141                 unregisterWithKeyboardManager(ks);
2142             }
2143             registered.clear();
2144         }
2145         // Updated the registered Hashtable.
2146         if (strokes != null && strokes.length > 0) {
2147             if (registered == null) {
2148                 registered = new Hashtable<KeyStroke, KeyStroke>(strokes.length);
2149                 putClientProperty(WHEN_IN_FOCUSED_WINDOW_BINDINGS, registered);
2150             }
2151             for (int counter = strokes.length - 1; counter >= 0; counter--) {
2152                 registered.put(strokes[counter], strokes[counter]);
2153             }
2154         }
2155         else {
2156             putClientProperty(WHEN_IN_FOCUSED_WINDOW_BINDINGS, null);
2157         }
2158     }
2159 
2160     /**
2161      * Unregisters all the previously registered
2162      * <code>WHEN_IN_FOCUSED_WINDOW</code> <code>KeyStroke</code> bindings.
2163      */
2164     private void unregisterWithKeyboardManager() {
2165         Hashtable<KeyStroke, KeyStroke> registered =
2166                 (Hashtable<KeyStroke, KeyStroke>)getClientProperty
2167                                 (WHEN_IN_FOCUSED_WINDOW_BINDINGS);
2168 
2169         if (registered != null && registered.size() > 0) {
2170             Enumeration<KeyStroke> keys = registered.keys();
2171 
2172             while (keys.hasMoreElements()) {
2173                 KeyStroke ks = keys.nextElement();
2174                 unregisterWithKeyboardManager(ks);
2175             }
2176         }
2177         putClientProperty(WHEN_IN_FOCUSED_WINDOW_BINDINGS, null);
2178     }
2179 
2180     /**
2181      * Invoked from <code>ComponentInputMap</code> when its bindings change.
2182      * If <code>inputMap</code> is the current <code>windowInputMap</code>
2183      * (or a parent of the window <code>InputMap</code>)
2184      * the <code>KeyboardManager</code> is notified of the new bindings.
2185      *
2186      * @param inputMap the map containing the new bindings
2187      */
2188     void componentInputMapChanged(ComponentInputMap inputMap) {
2189         InputMap km = getInputMap(WHEN_IN_FOCUSED_WINDOW, false);
2190 
2191         while (km != inputMap && km != null) {
2192             km = km.getParent();
2193         }
2194         if (km != null) {
2195             registerWithKeyboardManager(false);
2196         }
2197     }
2198 
2199     private void registerWithKeyboardManager(KeyStroke aKeyStroke) {
2200         KeyboardManager.getCurrentManager().registerKeyStroke(aKeyStroke,this);
2201     }
2202 
2203     private void unregisterWithKeyboardManager(KeyStroke aKeyStroke) {
2204         KeyboardManager.getCurrentManager().unregisterKeyStroke(aKeyStroke,
2205                                                                 this);
2206     }
2207 
2208     /**
2209      * This method is now obsolete, please use a combination of
2210      * <code>getActionMap()</code> and <code>getInputMap()</code> for
2211      * similar behavior.
2212      */
2213     public void registerKeyboardAction(ActionListener anAction,KeyStroke aKeyStroke,int aCondition) {
2214         registerKeyboardAction(anAction,null,aKeyStroke,aCondition);
2215     }
2216 
2217     /**
2218      * This method is now obsolete. To unregister an existing binding
2219      * you can either remove the binding from the
2220      * <code>ActionMap/InputMap</code>, or place a dummy binding the
2221      * <code>InputMap</code>. Removing the binding from the
2222      * <code>InputMap</code> allows bindings in parent <code>InputMap</code>s
2223      * to be active, whereas putting a dummy binding in the
2224      * <code>InputMap</code> effectively disables
2225      * the binding from ever happening.
2226      * <p>
2227      * Unregisters a keyboard action.
2228      * This will remove the binding from the <code>ActionMap</code>
2229      * (if it exists) as well as the <code>InputMap</code>s.
2230      */
2231     public void unregisterKeyboardAction(KeyStroke aKeyStroke) {
2232         ActionMap am = getActionMap(false);
2233         for (int counter = 0; counter < 3; counter++) {
2234             InputMap km = getInputMap(counter, false);
2235             if (km != null) {
2236                 Object actionID = km.get(aKeyStroke);
2237 
2238                 if (am != null && actionID != null) {
2239                     am.remove(actionID);
2240                 }
2241                 km.remove(aKeyStroke);
2242             }
2243         }
2244     }
2245 
2246     /**
2247      * Returns the <code>KeyStrokes</code> that will initiate
2248      * registered actions.
2249      *
2250      * @return an array of <code>KeyStroke</code> objects
2251      * @see #registerKeyboardAction
2252      */
2253     public KeyStroke[] getRegisteredKeyStrokes() {
2254         int[] counts = new int[3];
2255         KeyStroke[][] strokes = new KeyStroke[3][];
2256 
2257         for (int counter = 0; counter < 3; counter++) {
2258             InputMap km = getInputMap(counter, false);
2259             strokes[counter] = (km != null) ? km.allKeys() : null;
2260             counts[counter] = (strokes[counter] != null) ?
2261                                strokes[counter].length : 0;
2262         }
2263         KeyStroke[] retValue = new KeyStroke[counts[0] + counts[1] +
2264                                             counts[2]];
2265         for (int counter = 0, last = 0; counter < 3; counter++) {
2266             if (counts[counter] > 0) {
2267                 System.arraycopy(strokes[counter], 0, retValue, last,
2268                                  counts[counter]);
2269                 last += counts[counter];
2270             }
2271         }
2272         return retValue;
2273     }
2274 
2275     /**
2276      * Returns the condition that determines whether a registered action
2277      * occurs in response to the specified keystroke.
2278      * <p>
2279      * For Java 2 platform v1.3, a <code>KeyStroke</code> can be associated
2280      * with more than one condition.
2281      * For example, 'a' could be bound for the two
2282      * conditions <code>WHEN_FOCUSED</code> and
2283      * <code>WHEN_IN_FOCUSED_WINDOW</code> condition.
2284      *
2285      * @return the action-keystroke condition
2286      */
2287     public int getConditionForKeyStroke(KeyStroke aKeyStroke) {
2288         for (int counter = 0; counter < 3; counter++) {
2289             InputMap inputMap = getInputMap(counter, false);
2290             if (inputMap != null && inputMap.get(aKeyStroke) != null) {
2291                 return counter;
2292             }
2293         }
2294         return UNDEFINED_CONDITION;
2295     }
2296 
2297     /**
2298      * Returns the object that will perform the action registered for a
2299      * given keystroke.
2300      *
2301      * @return the <code>ActionListener</code>
2302      *          object invoked when the keystroke occurs
2303      */
2304     public ActionListener getActionForKeyStroke(KeyStroke aKeyStroke) {
2305         ActionMap am = getActionMap(false);
2306 
2307         if (am == null) {
2308             return null;
2309         }
2310         for (int counter = 0; counter < 3; counter++) {
2311             InputMap inputMap = getInputMap(counter, false);
2312             if (inputMap != null) {
2313                 Object actionBinding = inputMap.get(aKeyStroke);
2314 
2315                 if (actionBinding != null) {
2316                     Action action = am.get(actionBinding);
2317                     if (action instanceof ActionStandin) {
2318                         return ((ActionStandin)action).actionListener;
2319                     }
2320                     return action;
2321                 }
2322             }
2323         }
2324         return null;
2325     }
2326 
2327     /**
2328      * Unregisters all the bindings in the first tier <code>InputMaps</code>
2329      * and <code>ActionMap</code>. This has the effect of removing any
2330      * local bindings, and allowing the bindings defined in parent
2331      * <code>InputMap/ActionMaps</code>
2332      * (the UI is usually defined in the second tier) to persist.
2333      */
2334     public void resetKeyboardActions() {
2335         // Keys
2336         for (int counter = 0; counter < 3; counter++) {
2337             InputMap inputMap = getInputMap(counter, false);
2338 
2339             if (inputMap != null) {
2340                 inputMap.clear();
2341             }
2342         }
2343 
2344         // Actions
2345         ActionMap am = getActionMap(false);
2346 
2347         if (am != null) {
2348             am.clear();
2349         }
2350     }
2351 
2352     /**
2353      * Sets the <code>InputMap</code> to use under the condition
2354      * <code>condition</code> to
2355      * <code>map</code>. A <code>null</code> value implies you
2356      * do not want any bindings to be used, even from the UI. This will
2357      * not reinstall the UI <code>InputMap</code> (if there was one).
2358      * <code>condition</code> has one of the following values:
2359      * <ul>
2360      * <li><code>WHEN_IN_FOCUSED_WINDOW</code>
2361      * <li><code>WHEN_FOCUSED</code>
2362      * <li><code>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT</code>
2363      * </ul>
2364      * If <code>condition</code> is <code>WHEN_IN_FOCUSED_WINDOW</code>
2365      * and <code>map</code> is not a <code>ComponentInputMap</code>, an
2366      * <code>IllegalArgumentException</code> will be thrown.
2367      * Similarly, if <code>condition</code> is not one of the values
2368      * listed, an <code>IllegalArgumentException</code> will be thrown.
2369      *
2370      * @param condition one of the values listed above
2371      * @param map  the <code>InputMap</code> to use for the given condition
2372      * @exception IllegalArgumentException if <code>condition</code> is
2373      *          <code>WHEN_IN_FOCUSED_WINDOW</code> and <code>map</code>
2374      *          is not an instance of <code>ComponentInputMap</code>; or
2375      *          if <code>condition</code> is not one of the legal values
2376      *          specified above
2377      * @since 1.3
2378      */
2379     public final void setInputMap(int condition, InputMap map) {
2380         switch (condition) {
2381         case WHEN_IN_FOCUSED_WINDOW:
2382             if (map != null && !(map instanceof ComponentInputMap)) {
2383                 throw new IllegalArgumentException("WHEN_IN_FOCUSED_WINDOW InputMaps must be of type ComponentInputMap");
2384             }
2385             windowInputMap = (ComponentInputMap)map;
2386             setFlag(WIF_INPUTMAP_CREATED, true);
2387             registerWithKeyboardManager(false);
2388             break;
2389         case WHEN_ANCESTOR_OF_FOCUSED_COMPONENT:
2390             ancestorInputMap = map;
2391             setFlag(ANCESTOR_INPUTMAP_CREATED, true);
2392             break;
2393         case WHEN_FOCUSED:
2394             focusInputMap = map;
2395             setFlag(FOCUS_INPUTMAP_CREATED, true);
2396             break;
2397         default:
2398             throw new IllegalArgumentException("condition must be one of JComponent.WHEN_IN_FOCUSED_WINDOW, JComponent.WHEN_FOCUSED or JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT");
2399         }
2400     }
2401 
2402     /**
2403      * Returns the <code>InputMap</code> that is used during
2404      * <code>condition</code>.
2405      *
2406      * @param condition one of WHEN_IN_FOCUSED_WINDOW, WHEN_FOCUSED,
2407      *        WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
2408      * @return the <code>InputMap</code> for the specified
2409      *          <code>condition</code>
2410      * @since 1.3
2411      */
2412     public final InputMap getInputMap(int condition) {
2413         return getInputMap(condition, true);
2414     }
2415 
2416     /**
2417      * Returns the <code>InputMap</code> that is used when the
2418      * component has focus.
2419      * This is convenience method for <code>getInputMap(WHEN_FOCUSED)</code>.
2420      *
2421      * @return the <code>InputMap</code> used when the component has focus
2422      * @since 1.3
2423      */
2424     public final InputMap getInputMap() {
2425         return getInputMap(WHEN_FOCUSED, true);
2426     }
2427 
2428     /**
2429      * Sets the <code>ActionMap</code> to <code>am</code>. This does not set
2430      * the parent of the <code>am</code> to be the <code>ActionMap</code>
2431      * from the UI (if there was one), it is up to the caller to have done this.
2432      *
2433      * @param am  the new <code>ActionMap</code>
2434      * @since 1.3
2435      */
2436     public final void setActionMap(ActionMap am) {
2437         actionMap = am;
2438         setFlag(ACTIONMAP_CREATED, true);
2439     }
2440 
2441     /**
2442      * Returns the <code>ActionMap</code> used to determine what
2443      * <code>Action</code> to fire for particular <code>KeyStroke</code>
2444      * binding. The returned <code>ActionMap</code>, unless otherwise
2445      * set, will have the <code>ActionMap</code> from the UI set as the parent.
2446      *
2447      * @return the <code>ActionMap</code> containing the key/action bindings
2448      * @since 1.3
2449      */
2450     public final ActionMap getActionMap() {
2451         return getActionMap(true);
2452     }
2453 
2454     /**
2455      * Returns the <code>InputMap</code> to use for condition
2456      * <code>condition</code>.  If the <code>InputMap</code> hasn't
2457      * been created, and <code>create</code> is
2458      * true, it will be created.
2459      *
2460      * @param condition one of the following values:
2461      * <ul>
2462      * <li>JComponent.FOCUS_INPUTMAP_CREATED
2463      * <li>JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
2464      * <li>JComponent.WHEN_IN_FOCUSED_WINDOW
2465      * </ul>
2466      * @param create if true, create the <code>InputMap</code> if it
2467      *          is not already created
2468      * @return the <code>InputMap</code> for the given <code>condition</code>;
2469      *          if <code>create</code> is false and the <code>InputMap</code>
2470      *          hasn't been created, returns <code>null</code>
2471      * @exception IllegalArgumentException if <code>condition</code>
2472      *          is not one of the legal values listed above
2473      */
2474     final InputMap getInputMap(int condition, boolean create) {
2475         switch (condition) {
2476         case WHEN_FOCUSED:
2477             if (getFlag(FOCUS_INPUTMAP_CREATED)) {
2478                 return focusInputMap;
2479             }
2480             // Hasn't been created yet.
2481             if (create) {
2482                 InputMap km = new InputMap();
2483                 setInputMap(condition, km);
2484                 return km;
2485             }
2486             break;
2487         case WHEN_ANCESTOR_OF_FOCUSED_COMPONENT:
2488             if (getFlag(ANCESTOR_INPUTMAP_CREATED)) {
2489                 return ancestorInputMap;
2490             }
2491             // Hasn't been created yet.
2492             if (create) {
2493                 InputMap km = new InputMap();
2494                 setInputMap(condition, km);
2495                 return km;
2496             }
2497             break;
2498         case WHEN_IN_FOCUSED_WINDOW:
2499             if (getFlag(WIF_INPUTMAP_CREATED)) {
2500                 return windowInputMap;
2501             }
2502             // Hasn't been created yet.
2503             if (create) {
2504                 ComponentInputMap km = new ComponentInputMap(this);
2505                 setInputMap(condition, km);
2506                 return km;
2507             }
2508             break;
2509         default:
2510             throw new IllegalArgumentException("condition must be one of JComponent.WHEN_IN_FOCUSED_WINDOW, JComponent.WHEN_FOCUSED or JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT");
2511         }
2512         return null;
2513     }
2514 
2515     /**
2516      * Finds and returns the appropriate <code>ActionMap</code>.
2517      *
2518      * @param create if true, create the <code>ActionMap</code> if it
2519      *          is not already created
2520      * @return the <code>ActionMap</code> for this component; if the
2521      *          <code>create</code> flag is false and there is no
2522      *          current <code>ActionMap</code>, returns <code>null</code>
2523      */
2524     final ActionMap getActionMap(boolean create) {
2525         if (getFlag(ACTIONMAP_CREATED)) {
2526             return actionMap;
2527         }
2528         // Hasn't been created.
2529         if (create) {
2530             ActionMap am = new ActionMap();
2531             setActionMap(am);
2532             return am;
2533         }
2534         return null;
2535     }
2536 
2537     /**
2538      * Returns the baseline.  The baseline is measured from the top of
2539      * the component.  This method is primarily meant for
2540      * <code>LayoutManager</code>s to align components along their
2541      * baseline.  A return value less than 0 indicates this component
2542      * does not have a reasonable baseline and that
2543      * <code>LayoutManager</code>s should not align this component on
2544      * its baseline.
2545      * <p>
2546      * This method calls into the <code>ComponentUI</code> method of the
2547      * same name.  If this component does not have a <code>ComponentUI</code>
2548      * -1 will be returned.  If a value &gt;= 0 is
2549      * returned, then the component has a valid baseline for any
2550      * size &gt;= the minimum size and <code>getBaselineResizeBehavior</code>
2551      * can be used to determine how the baseline changes with size.
2552      *
2553      * @throws IllegalArgumentException {@inheritDoc}
2554      * @see #getBaselineResizeBehavior
2555      * @see java.awt.FontMetrics
2556      * @since 1.6
2557      */
2558     public int getBaseline(int width, int height) {
2559         // check size.
2560         super.getBaseline(width, height);
2561         if (ui != null) {
2562             return ui.getBaseline(this, width, height);
2563         }
2564         return -1;
2565     }
2566 
2567     /**
2568      * Returns an enum indicating how the baseline of the component
2569      * changes as the size changes.  This method is primarily meant for
2570      * layout managers and GUI builders.
2571      * <p>
2572      * This method calls into the <code>ComponentUI</code> method of
2573      * the same name.  If this component does not have a
2574      * <code>ComponentUI</code>
2575      * <code>BaselineResizeBehavior.OTHER</code> will be
2576      * returned.  Subclasses should
2577      * never return <code>null</code>; if the baseline can not be
2578      * calculated return <code>BaselineResizeBehavior.OTHER</code>.  Callers
2579      * should first ask for the baseline using
2580      * <code>getBaseline</code> and if a value &gt;= 0 is returned use
2581      * this method.  It is acceptable for this method to return a
2582      * value other than <code>BaselineResizeBehavior.OTHER</code> even if
2583      * <code>getBaseline</code> returns a value less than 0.
2584      *
2585      * @see #getBaseline(int, int)
2586      * @since 1.6
2587      */
2588     public BaselineResizeBehavior getBaselineResizeBehavior() {
2589         if (ui != null) {
2590             return ui.getBaselineResizeBehavior(this);
2591         }
2592         return BaselineResizeBehavior.OTHER;
2593     }
2594 
2595     /**
2596      * In release 1.4, the focus subsystem was rearchitected.
2597      * For more information, see
2598      * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
2599      * How to Use the Focus Subsystem</a>,
2600      * a section in <em>The Java Tutorial</em>.
2601      * <p>
2602      * Requests focus on this <code>JComponent</code>'s
2603      * <code>FocusTraversalPolicy</code>'s default <code>Component</code>.
2604      * If this <code>JComponent</code> is a focus cycle root, then its
2605      * <code>FocusTraversalPolicy</code> is used. Otherwise, the
2606      * <code>FocusTraversalPolicy</code> of this <code>JComponent</code>'s
2607      * focus-cycle-root ancestor is used.
2608      *
2609      * @see java.awt.FocusTraversalPolicy#getDefaultComponent
2610      * @deprecated As of 1.4, replaced by
2611      * <code>FocusTraversalPolicy.getDefaultComponent(Container).requestFocus()</code>
2612      */
2613     @Deprecated
2614     public boolean requestDefaultFocus() {
2615         Container nearestRoot =
2616             (isFocusCycleRoot()) ? this : getFocusCycleRootAncestor();
2617         if (nearestRoot == null) {
2618             return false;
2619         }
2620         Component comp = nearestRoot.getFocusTraversalPolicy().
2621             getDefaultComponent(nearestRoot);
2622         if (comp != null) {
2623             comp.requestFocus();
2624             return true;
2625         } else {
2626             return false;
2627         }
2628     }
2629 
2630     /**
2631      * Makes the component visible or invisible.
2632      * Overrides <code>Component.setVisible</code>.
2633      *
2634      * @param aFlag  true to make the component visible; false to
2635      *          make it invisible
2636      *
2637      * @beaninfo
2638      *    attribute: visualUpdate true
2639      */
2640     public void setVisible(boolean aFlag) {
2641         if (aFlag != isVisible()) {
2642             super.setVisible(aFlag);
2643             if (aFlag) {
2644                 Container parent = getParent();
2645                 if (parent != null) {
2646                     Rectangle r = getBounds();
2647                     parent.repaint(r.x, r.y, r.width, r.height);
2648                 }
2649                 revalidate();
2650             }
2651         }
2652     }
2653 
2654     /**
2655      * Sets whether or not this component is enabled.
2656      * A component that is enabled may respond to user input,
2657      * while a component that is not enabled cannot respond to
2658      * user input.  Some components may alter their visual
2659      * representation when they are disabled in order to
2660      * provide feedback to the user that they cannot take input.
2661      * <p>Note: Disabling a component does not disable its children.
2662      *
2663      * <p>Note: Disabling a lightweight component does not prevent it from
2664      * receiving MouseEvents.
2665      *
2666      * @param enabled true if this component should be enabled, false otherwise
2667      * @see java.awt.Component#isEnabled
2668      * @see java.awt.Component#isLightweight
2669      *
2670      * @beaninfo
2671      *    preferred: true
2672      *        bound: true
2673      *    attribute: visualUpdate true
2674      *  description: The enabled state of the component.
2675      */
2676     public void setEnabled(boolean enabled) {
2677         boolean oldEnabled = isEnabled();
2678         super.setEnabled(enabled);
2679         firePropertyChange("enabled", oldEnabled, enabled);
2680         if (enabled != oldEnabled) {
2681             repaint();
2682         }
2683     }
2684 
2685     /**
2686      * Sets the foreground color of this component.  It is up to the
2687      * look and feel to honor this property, some may choose to ignore
2688      * it.
2689      *
2690      * @param fg  the desired foreground <code>Color</code>
2691      * @see java.awt.Component#getForeground
2692      *
2693      * @beaninfo
2694      *    preferred: true
2695      *        bound: true
2696      *    attribute: visualUpdate true
2697      *  description: The foreground color of the component.
2698      */
2699     public void setForeground(Color fg) {
2700         Color oldFg = getForeground();
2701         super.setForeground(fg);
2702         if ((oldFg != null) ? !oldFg.equals(fg) : ((fg != null) && !fg.equals(oldFg))) {
2703             // foreground already bound in AWT1.2
2704             repaint();
2705         }
2706     }
2707 
2708     /**
2709      * Sets the background color of this component.  The background
2710      * color is used only if the component is opaque, and only
2711      * by subclasses of <code>JComponent</code> or
2712      * <code>ComponentUI</code> implementations.  Direct subclasses of
2713      * <code>JComponent</code> must override
2714      * <code>paintComponent</code> to honor this property.
2715      * <p>
2716      * It is up to the look and feel to honor this property, some may
2717      * choose to ignore it.
2718      *
2719      * @param bg the desired background <code>Color</code>
2720      * @see java.awt.Component#getBackground
2721      * @see #setOpaque
2722      *
2723      * @beaninfo
2724      *    preferred: true
2725      *        bound: true
2726      *    attribute: visualUpdate true
2727      *  description: The background color of the component.
2728      */
2729     public void setBackground(Color bg) {
2730         Color oldBg = getBackground();
2731         super.setBackground(bg);
2732         if ((oldBg != null) ? !oldBg.equals(bg) : ((bg != null) && !bg.equals(oldBg))) {
2733             // background already bound in AWT1.2
2734             repaint();
2735         }
2736     }
2737 
2738     /**
2739      * Sets the font for this component.
2740      *
2741      * @param font the desired <code>Font</code> for this component
2742      * @see java.awt.Component#getFont
2743      *
2744      * @beaninfo
2745      *    preferred: true
2746      *        bound: true
2747      *    attribute: visualUpdate true
2748      *  description: The font for the component.
2749      */
2750     public void setFont(Font font) {
2751         Font oldFont = getFont();
2752         super.setFont(font);
2753         // font already bound in AWT1.2
2754         if (font != oldFont) {
2755             revalidate();
2756             repaint();
2757         }
2758     }
2759 
2760     /**
2761      * Returns the default locale used to initialize each JComponent's
2762      * locale property upon creation.
2763      *
2764      * The default locale has "AppContext" scope so that applets (and
2765      * potentially multiple lightweight applications running in a single VM)
2766      * can have their own setting. An applet can safely alter its default
2767      * locale because it will have no affect on other applets (or the browser).
2768      *
2769      * @return the default <code>Locale</code>.
2770      * @see #setDefaultLocale
2771      * @see java.awt.Component#getLocale
2772      * @see #setLocale
2773      * @since 1.4
2774      */
2775     static public Locale getDefaultLocale() {
2776         Locale l = (Locale) SwingUtilities.appContextGet(defaultLocale);
2777         if( l == null ) {
2778             //REMIND(bcb) choosing the default value is more complicated
2779             //than this.
2780             l = Locale.getDefault();
2781             JComponent.setDefaultLocale( l );
2782         }
2783         return l;
2784     }
2785 
2786 
2787     /**
2788      * Sets the default locale used to initialize each JComponent's locale
2789      * property upon creation.  The initial value is the VM's default locale.
2790      *
2791      * The default locale has "AppContext" scope so that applets (and
2792      * potentially multiple lightweight applications running in a single VM)
2793      * can have their own setting. An applet can safely alter its default
2794      * locale because it will have no affect on other applets (or the browser).
2795      *
2796      * @param l the desired default <code>Locale</code> for new components.
2797      * @see #getDefaultLocale
2798      * @see java.awt.Component#getLocale
2799      * @see #setLocale
2800      * @since 1.4
2801      */
2802     static public void setDefaultLocale( Locale l ) {
2803         SwingUtilities.appContextPut(defaultLocale, l);
2804     }
2805 
2806 
2807     /**
2808      * Processes any key events that the component itself
2809      * recognizes.  This is called after the focus
2810      * manager and any interested listeners have been
2811      * given a chance to steal away the event.  This
2812      * method is called only if the event has not
2813      * yet been consumed.  This method is called prior
2814      * to the keyboard UI logic.
2815      * <p>
2816      * This method is implemented to do nothing.  Subclasses would
2817      * normally override this method if they process some
2818      * key events themselves.  If the event is processed,
2819      * it should be consumed.
2820      */
2821     protected void processComponentKeyEvent(KeyEvent e) {
2822     }
2823 
2824     /** Overrides <code>processKeyEvent</code> to process events. **/
2825     protected void processKeyEvent(KeyEvent e) {
2826       boolean result;
2827       boolean shouldProcessKey;
2828 
2829       // This gives the key event listeners a crack at the event
2830       super.processKeyEvent(e);
2831 
2832       // give the component itself a crack at the event
2833       if (! e.isConsumed()) {
2834           processComponentKeyEvent(e);
2835       }
2836 
2837       shouldProcessKey = KeyboardState.shouldProcess(e);
2838 
2839       if(e.isConsumed()) {
2840         return;
2841       }
2842 
2843       if (shouldProcessKey && processKeyBindings(e, e.getID() ==
2844                                                  KeyEvent.KEY_PRESSED)) {
2845           e.consume();
2846       }
2847     }
2848 
2849     /**
2850      * Invoked to process the key bindings for <code>ks</code> as the result
2851      * of the <code>KeyEvent</code> <code>e</code>. This obtains
2852      * the appropriate <code>InputMap</code>,
2853      * gets the binding, gets the action from the <code>ActionMap</code>,
2854      * and then (if the action is found and the component
2855      * is enabled) invokes <code>notifyAction</code> to notify the action.
2856      *
2857      * @param ks  the <code>KeyStroke</code> queried
2858      * @param e the <code>KeyEvent</code>
2859      * @param condition one of the following values:
2860      * <ul>
2861      * <li>JComponent.WHEN_FOCUSED
2862      * <li>JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
2863      * <li>JComponent.WHEN_IN_FOCUSED_WINDOW
2864      * </ul>
2865      * @param pressed true if the key is pressed
2866      * @return true if there was a binding to an action, and the action
2867      *         was enabled
2868      *
2869      * @since 1.3
2870      */
2871     protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
2872                                         int condition, boolean pressed) {
2873         InputMap map = getInputMap(condition, false);
2874         ActionMap am = getActionMap(false);
2875 
2876         if(map != null && am != null && isEnabled()) {
2877             Object binding = map.get(ks);
2878             Action action = (binding == null) ? null : am.get(binding);
2879             if (action != null) {
2880                 return SwingUtilities.notifyAction(action, ks, e, this,
2881                                                    e.getModifiers());
2882             }
2883         }
2884         return false;
2885     }
2886 
2887     /**
2888      * This is invoked as the result of a <code>KeyEvent</code>
2889      * that was not consumed by the <code>FocusManager</code>,
2890      * <code>KeyListeners</code>, or the component. It will first try
2891      * <code>WHEN_FOCUSED</code> bindings,
2892      * then <code>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT</code> bindings,
2893      * and finally <code>WHEN_IN_FOCUSED_WINDOW</code> bindings.
2894      *
2895      * @param e the unconsumed <code>KeyEvent</code>
2896      * @param pressed true if the key is pressed
2897      * @return true if there is a key binding for <code>e</code>
2898      */
2899     boolean processKeyBindings(KeyEvent e, boolean pressed) {
2900       if (!SwingUtilities.isValidKeyEventForKeyBindings(e)) {
2901           return false;
2902       }
2903       // Get the KeyStroke
2904       // There may be two keystrokes associated with a low-level key event;
2905       // in this case a keystroke made of an extended key code has a priority.
2906       KeyStroke ks;
2907       KeyStroke ksE = null;
2908 
2909       if (e.getID() == KeyEvent.KEY_TYPED) {
2910           ks = KeyStroke.getKeyStroke(e.getKeyChar());
2911       }
2912       else {
2913           ks = KeyStroke.getKeyStroke(e.getKeyCode(),e.getModifiers(),
2914                                     (pressed ? false:true));
2915           if (e.getKeyCode() != e.getExtendedKeyCode()) {
2916               ksE = KeyStroke.getKeyStroke(e.getExtendedKeyCode(),e.getModifiers(),
2917                                     (pressed ? false:true));
2918           }
2919       }
2920 
2921       // Do we have a key binding for e?
2922       // If we have a binding by an extended code, use it.
2923       // If not, check for regular code binding.
2924       if(ksE != null && processKeyBinding(ksE, e, WHEN_FOCUSED, pressed)) {
2925           return true;
2926       }
2927       if(processKeyBinding(ks, e, WHEN_FOCUSED, pressed))
2928           return true;
2929 
2930       /* We have no key binding. Let's try the path from our parent to the
2931        * window excluded. We store the path components so we can avoid
2932        * asking the same component twice.
2933        */
2934       Container parent = this;
2935       while (parent != null && !(parent instanceof Window) &&
2936              !(parent instanceof Applet)) {
2937           if(parent instanceof JComponent) {
2938               if(ksE != null && ((JComponent)parent).processKeyBinding(ksE, e,
2939                                WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, pressed))
2940                   return true;
2941               if(((JComponent)parent).processKeyBinding(ks, e,
2942                                WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, pressed))
2943                   return true;
2944           }
2945           // This is done so that the children of a JInternalFrame are
2946           // given precedence for WHEN_IN_FOCUSED_WINDOW bindings before
2947           // other components WHEN_IN_FOCUSED_WINDOW bindings. This also gives
2948           // more precedence to the WHEN_IN_FOCUSED_WINDOW bindings of the
2949           // JInternalFrame's children vs the
2950           // WHEN_ANCESTOR_OF_FOCUSED_COMPONENT bindings of the parents.
2951           // maybe generalize from JInternalFrame (like isFocusCycleRoot).
2952           if ((parent instanceof JInternalFrame) &&
2953               JComponent.processKeyBindingsForAllComponents(e,parent,pressed)){
2954               return true;
2955           }
2956           parent = parent.getParent();
2957       }
2958 
2959       /* No components between the focused component and the window is
2960        * actually interested by the key event. Let's try the other
2961        * JComponent in this window.
2962        */
2963       if(parent != null) {
2964         return JComponent.processKeyBindingsForAllComponents(e,parent,pressed);
2965       }
2966       return false;
2967     }
2968 
2969     static boolean processKeyBindingsForAllComponents(KeyEvent e,
2970                                       Container container, boolean pressed) {
2971         while (true) {
2972             if (KeyboardManager.getCurrentManager().fireKeyboardAction(
2973                                 e, pressed, container)) {
2974                 return true;
2975             }
2976             if (container instanceof Popup.HeavyWeightWindow) {
2977                 container = ((Window)container).getOwner();
2978             }
2979             else {
2980                 return false;
2981             }
2982         }
2983     }
2984 
2985     /**
2986      * Registers the text to display in a tool tip.
2987      * The text displays when the cursor lingers over the component.
2988      * <p>
2989      * See <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/tooltip.html">How to Use Tool Tips</a>
2990      * in <em>The Java Tutorial</em>
2991      * for further documentation.
2992      *
2993      * @param text  the string to display; if the text is <code>null</code>,
2994      *              the tool tip is turned off for this component
2995      * @see #TOOL_TIP_TEXT_KEY
2996      * @beaninfo
2997      *   preferred: true
2998      * description: The text to display in a tool tip.
2999      */
3000     public void setToolTipText(String text) {
3001         String oldText = getToolTipText();
3002         putClientProperty(TOOL_TIP_TEXT_KEY, text);
3003         ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
3004         if (text != null) {
3005             if (oldText == null) {
3006                 toolTipManager.registerComponent(this);
3007             }
3008         } else {
3009             toolTipManager.unregisterComponent(this);
3010         }
3011     }
3012 
3013     /**
3014      * Returns the tooltip string that has been set with
3015      * <code>setToolTipText</code>.
3016      *
3017      * @return the text of the tool tip
3018      * @see #TOOL_TIP_TEXT_KEY
3019      */
3020     public String getToolTipText() {
3021         return (String)getClientProperty(TOOL_TIP_TEXT_KEY);
3022     }
3023 
3024 
3025     /**
3026      * Returns the string to be used as the tooltip for <i>event</i>.
3027      * By default this returns any string set using
3028      * <code>setToolTipText</code>.  If a component provides
3029      * more extensive API to support differing tooltips at different locations,
3030      * this method should be overridden.
3031      */
3032     public String getToolTipText(MouseEvent event) {
3033         return getToolTipText();
3034     }
3035 
3036     /**
3037      * Returns the tooltip location in this component's coordinate system.
3038      * If <code>null</code> is returned, Swing will choose a location.
3039      * The default implementation returns <code>null</code>.
3040      *
3041      * @param event  the <code>MouseEvent</code> that caused the
3042      *          <code>ToolTipManager</code> to show the tooltip
3043      * @return always returns <code>null</code>
3044      */
3045     public Point getToolTipLocation(MouseEvent event) {
3046         return null;
3047     }
3048 
3049     /**
3050      * Returns the preferred location to display the popup menu in this
3051      * component's coordinate system. It is up to the look and feel to
3052      * honor this property, some may choose to ignore it.
3053      * If {@code null}, the look and feel will choose a suitable location.
3054      *
3055      * @param event the {@code MouseEvent} that triggered the popup to be
3056      *        shown, or {@code null} if the popup is not being shown as the
3057      *        result of a mouse event
3058      * @return location to display the {@code JPopupMenu}, or {@code null}
3059      * @since 1.5
3060      */
3061     public Point getPopupLocation(MouseEvent event) {
3062         return null;
3063     }
3064 
3065 
3066     /**
3067      * Returns the instance of <code>JToolTip</code> that should be used
3068      * to display the tooltip.
3069      * Components typically would not override this method,
3070      * but it can be used to
3071      * cause different tooltips to be displayed differently.
3072      *
3073      * @return the <code>JToolTip</code> used to display this toolTip
3074      */
3075     public JToolTip createToolTip() {
3076         JToolTip tip = new JToolTip();
3077         tip.setComponent(this);
3078         return tip;
3079     }
3080 
3081     /**
3082      * Forwards the <code>scrollRectToVisible()</code> message to the
3083      * <code>JComponent</code>'s parent. Components that can service
3084      * the request, such as <code>JViewport</code>,
3085      * override this method and perform the scrolling.
3086      *
3087      * @param aRect the visible <code>Rectangle</code>
3088      * @see JViewport
3089      */
3090     public void scrollRectToVisible(Rectangle aRect) {
3091         Container parent;
3092         int dx = getX(), dy = getY();
3093 
3094         for (parent = getParent();
3095                  !(parent == null) &&
3096                  !(parent instanceof JComponent) &&
3097                  !(parent instanceof CellRendererPane);
3098              parent = parent.getParent()) {
3099              Rectangle bounds = parent.getBounds();
3100 
3101              dx += bounds.x;
3102              dy += bounds.y;
3103         }
3104 
3105         if (!(parent == null) && !(parent instanceof CellRendererPane)) {
3106             aRect.x += dx;
3107             aRect.y += dy;
3108 
3109             ((JComponent)parent).scrollRectToVisible(aRect);
3110             aRect.x -= dx;
3111             aRect.y -= dy;
3112         }
3113     }
3114 
3115     /**
3116      * Sets the <code>autoscrolls</code> property.
3117      * If <code>true</code> mouse dragged events will be
3118      * synthetically generated when the mouse is dragged
3119      * outside of the component's bounds and mouse motion
3120      * has paused (while the button continues to be held
3121      * down). The synthetic events make it appear that the
3122      * drag gesture has resumed in the direction established when
3123      * the component's boundary was crossed.  Components that
3124      * support autoscrolling must handle <code>mouseDragged</code>
3125      * events by calling <code>scrollRectToVisible</code> with a
3126      * rectangle that contains the mouse event's location.  All of
3127      * the Swing components that support item selection and are
3128      * typically displayed in a <code>JScrollPane</code>
3129      * (<code>JTable</code>, <code>JList</code>, <code>JTree</code>,
3130      * <code>JTextArea</code>, and <code>JEditorPane</code>)
3131      * already handle mouse dragged events in this way.  To enable
3132      * autoscrolling in any other component, add a mouse motion
3133      * listener that calls <code>scrollRectToVisible</code>.
3134      * For example, given a <code>JPanel</code>, <code>myPanel</code>:
3135      * <pre>
3136      * MouseMotionListener doScrollRectToVisible = new MouseMotionAdapter() {
3137      *     public void mouseDragged(MouseEvent e) {
3138      *        Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1);
3139      *        ((JPanel)e.getSource()).scrollRectToVisible(r);
3140      *    }
3141      * };
3142      * myPanel.addMouseMotionListener(doScrollRectToVisible);
3143      * </pre>
3144      * The default value of the <code>autoScrolls</code>
3145      * property is <code>false</code>.
3146      *
3147      * @param autoscrolls if true, synthetic mouse dragged events
3148      *   are generated when the mouse is dragged outside of a component's
3149      *   bounds and the mouse button continues to be held down; otherwise
3150      *   false
3151      * @see #getAutoscrolls
3152      * @see JViewport
3153      * @see JScrollPane
3154      *
3155      * @beaninfo
3156      *      expert: true
3157      * description: Determines if this component automatically scrolls its contents when dragged.
3158      */
3159     public void setAutoscrolls(boolean autoscrolls) {
3160         setFlag(AUTOSCROLLS_SET, true);
3161         if (this.autoscrolls != autoscrolls) {
3162             this.autoscrolls = autoscrolls;
3163             if (autoscrolls) {
3164                 enableEvents(AWTEvent.MOUSE_EVENT_MASK);
3165                 enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
3166             }
3167             else {
3168                 Autoscroller.stop(this);
3169             }
3170         }
3171     }
3172 
3173     /**
3174      * Gets the <code>autoscrolls</code> property.
3175      *
3176      * @return the value of the <code>autoscrolls</code> property
3177      * @see JViewport
3178      * @see #setAutoscrolls
3179      */
3180     public boolean getAutoscrolls() {
3181         return autoscrolls;
3182     }
3183 
3184     /**
3185      * Sets the {@code TransferHandler}, which provides support for transfer
3186      * of data into and out of this component via cut/copy/paste and drag
3187      * and drop. This may be {@code null} if the component does not support
3188      * data transfer operations.
3189      * <p>
3190      * If the new {@code TransferHandler} is not {@code null}, this method
3191      * also installs a <b>new</b> {@code DropTarget} on the component to
3192      * activate drop handling through the {@code TransferHandler} and activate
3193      * any built-in support (such as calculating and displaying potential drop
3194      * locations). If you do not wish for this component to respond in any way
3195      * to drops, you can disable drop support entirely either by removing the
3196      * drop target ({@code setDropTarget(null)}) or by de-activating it
3197      * ({@code getDropTaget().setActive(false)}).
3198      * <p>
3199      * If the new {@code TransferHandler} is {@code null}, this method removes
3200      * the drop target.
3201      * <p>
3202      * Under two circumstances, this method does not modify the drop target:
3203      * First, if the existing drop target on this component was explicitly
3204      * set by the developer to a {@code non-null} value. Second, if the
3205      * system property {@code suppressSwingDropSupport} is {@code true}. The
3206      * default value for the system property is {@code false}.
3207      * <p>
3208      * Please see
3209      * <a href="http://docs.oracle.com/javase/tutorial/uiswing/dnd/index.html">
3210      * How to Use Drag and Drop and Data Transfer</a>,
3211      * a section in <em>The Java Tutorial</em>, for more information.
3212      *
3213      * @param newHandler the new {@code TransferHandler}
3214      *
3215      * @see TransferHandler
3216      * @see #getTransferHandler
3217      * @since 1.4
3218      * @beaninfo
3219      *        bound: true
3220      *       hidden: true
3221      *  description: Mechanism for transfer of data to and from the component
3222      */
3223     public void setTransferHandler(TransferHandler newHandler) {
3224         TransferHandler oldHandler = (TransferHandler)getClientProperty(
3225                                       JComponent_TRANSFER_HANDLER);
3226         putClientProperty(JComponent_TRANSFER_HANDLER, newHandler);
3227 
3228         SwingUtilities.installSwingDropTargetAsNecessary(this, newHandler);
3229         firePropertyChange("transferHandler", oldHandler, newHandler);
3230     }
3231 
3232     /**
3233      * Gets the <code>transferHandler</code> property.
3234      *
3235      * @return  the value of the <code>transferHandler</code> property
3236      *
3237      * @see TransferHandler
3238      * @see #setTransferHandler
3239      * @since 1.4
3240      */
3241     public TransferHandler getTransferHandler() {
3242         return (TransferHandler)getClientProperty(JComponent_TRANSFER_HANDLER);
3243     }
3244 
3245     /**
3246      * Calculates a custom drop location for this type of component,
3247      * representing where a drop at the given point should insert data.
3248      * <code>null</code> is returned if this component doesn't calculate
3249      * custom drop locations. In this case, <code>TransferHandler</code>
3250      * will provide a default <code>DropLocation</code> containing just
3251      * the point.
3252      *
3253      * @param p the point to calculate a drop location for
3254      * @return the drop location, or <code>null</code>
3255      */
3256     TransferHandler.DropLocation dropLocationForPoint(Point p) {
3257         return null;
3258     }
3259 
3260     /**
3261      * Called to set or clear the drop location during a DnD operation.
3262      * In some cases, the component may need to use its internal selection
3263      * temporarily to indicate the drop location. To help facilitate this,
3264      * this method returns and accepts as a parameter a state object.
3265      * This state object can be used to store, and later restore, the selection
3266      * state. Whatever this method returns will be passed back to it in
3267      * future calls, as the state parameter. If it wants the DnD system to
3268      * continue storing the same state, it must pass it back every time.
3269      * Here's how this is used:
3270      * <p>
3271      * Let's say that on the first call to this method the component decides
3272      * to save some state (because it is about to use the selection to show
3273      * a drop index). It can return a state object to the caller encapsulating
3274      * any saved selection state. On a second call, let's say the drop location
3275      * is being changed to something else. The component doesn't need to
3276      * restore anything yet, so it simply passes back the same state object
3277      * to have the DnD system continue storing it. Finally, let's say this
3278      * method is messaged with <code>null</code>. This means DnD
3279      * is finished with this component for now, meaning it should restore
3280      * state. At this point, it can use the state parameter to restore
3281      * said state, and of course return <code>null</code> since there's
3282      * no longer anything to store.
3283      *
3284      * @param location the drop location (as calculated by
3285      *        <code>dropLocationForPoint</code>) or <code>null</code>
3286      *        if there's no longer a valid drop location
3287      * @param state the state object saved earlier for this component,
3288      *        or <code>null</code>
3289      * @param forDrop whether or not the method is being called because an
3290      *        actual drop occurred
3291      * @return any saved state for this component, or <code>null</code> if none
3292      */
3293     Object setDropLocation(TransferHandler.DropLocation location,
3294                            Object state,
3295                            boolean forDrop) {
3296 
3297         return null;
3298     }
3299 
3300     /**
3301      * Called to indicate to this component that DnD is done.
3302      * Needed by <code>JTree</code>.
3303      */
3304     void dndDone() {
3305     }
3306 
3307     /**
3308      * Processes mouse events occurring on this component by
3309      * dispatching them to any registered
3310      * <code>MouseListener</code> objects, refer to
3311      * {@link java.awt.Component#processMouseEvent(MouseEvent)}
3312      * for a complete description of this method.
3313      *
3314      * @param       e the mouse event
3315      * @see         java.awt.Component#processMouseEvent
3316      * @since       1.5
3317      */
3318     protected void processMouseEvent(MouseEvent e) {
3319         if (autoscrolls && e.getID() == MouseEvent.MOUSE_RELEASED) {
3320             Autoscroller.stop(this);
3321         }
3322         super.processMouseEvent(e);
3323     }
3324 
3325     /**
3326      * Processes mouse motion events, such as MouseEvent.MOUSE_DRAGGED.
3327      *
3328      * @param e the <code>MouseEvent</code>
3329      * @see MouseEvent
3330      */
3331     protected void processMouseMotionEvent(MouseEvent e) {
3332         boolean dispatch = true;
3333         if (autoscrolls && e.getID() == MouseEvent.MOUSE_DRAGGED) {
3334             // We don't want to do the drags when the mouse moves if we're
3335             // autoscrolling.  It makes it feel spastic.
3336             dispatch = !Autoscroller.isRunning(this);
3337             Autoscroller.processMouseDragged(e);
3338         }
3339         if (dispatch) {
3340             super.processMouseMotionEvent(e);
3341         }
3342     }
3343 
3344     // Inner classes can't get at this method from a super class
3345     void superProcessMouseMotionEvent(MouseEvent e) {
3346         super.processMouseMotionEvent(e);
3347     }
3348 
3349     /**
3350      * This is invoked by the <code>RepaintManager</code> if
3351      * <code>createImage</code> is called on the component.
3352      *
3353      * @param newValue true if the double buffer image was created from this component
3354      */
3355     void setCreatedDoubleBuffer(boolean newValue) {
3356         setFlag(CREATED_DOUBLE_BUFFER, newValue);
3357     }
3358 
3359     /**
3360      * Returns true if the <code>RepaintManager</code>
3361      * created the double buffer image from the component.
3362      *
3363      * @return true if this component had a double buffer image, false otherwise
3364      */
3365     boolean getCreatedDoubleBuffer() {
3366         return getFlag(CREATED_DOUBLE_BUFFER);
3367     }
3368 
3369     /**
3370      * <code>ActionStandin</code> is used as a standin for
3371      * <code>ActionListeners</code> that are
3372      * added via <code>registerKeyboardAction</code>.
3373      */
3374     final class ActionStandin implements Action {
3375         private final ActionListener actionListener;
3376         private final String command;
3377         // This will be non-null if actionListener is an Action.
3378         private final Action action;
3379 
3380         ActionStandin(ActionListener actionListener, String command) {
3381             this.actionListener = actionListener;
3382             if (actionListener instanceof Action) {
3383                 this.action = (Action)actionListener;
3384             }
3385             else {
3386                 this.action = null;
3387             }
3388             this.command = command;
3389         }
3390 
3391         public Object getValue(String key) {
3392             if (key != null) {
3393                 if (key.equals(Action.ACTION_COMMAND_KEY)) {
3394                     return command;
3395                 }
3396                 if (action != null) {
3397                     return action.getValue(key);
3398                 }
3399                 if (key.equals(NAME)) {
3400                     return "ActionStandin";
3401                 }
3402             }
3403             return null;
3404         }
3405 
3406         public boolean isEnabled() {
3407             if (actionListener == null) {
3408                 // This keeps the old semantics where
3409                 // registerKeyboardAction(null) would essentialy remove
3410                 // the binding. We don't remove the binding from the
3411                 // InputMap as that would still allow parent InputMaps
3412                 // bindings to be accessed.
3413                 return false;
3414             }
3415             if (action == null) {
3416                 return true;
3417             }
3418             return action.isEnabled();
3419         }
3420 
3421         public void actionPerformed(ActionEvent ae) {
3422             if (actionListener != null) {
3423                 actionListener.actionPerformed(ae);
3424             }
3425         }
3426 
3427         // We don't allow any values to be added.
3428         public void putValue(String key, Object value) {}
3429 
3430         // Does nothing, our enabledness is determiend from our asociated
3431         // action.
3432         public void setEnabled(boolean b) { }
3433 
3434         public void addPropertyChangeListener
3435                     (PropertyChangeListener listener) {}
3436         public void removePropertyChangeListener
3437                           (PropertyChangeListener listener) {}
3438     }
3439 
3440 
3441     // This class is used by the KeyboardState class to provide a single
3442     // instance that can be stored in the AppContext.
3443     static final class IntVector {
3444         int array[] = null;
3445         int count = 0;
3446         int capacity = 0;
3447 
3448         int size() {
3449             return count;
3450         }
3451 
3452         int elementAt(int index) {
3453             return array[index];
3454         }
3455 
3456         void addElement(int value) {
3457             if (count == capacity) {
3458                 capacity = (capacity + 2) * 2;
3459                 int[] newarray = new int[capacity];
3460                 if (count > 0) {
3461                     System.arraycopy(array, 0, newarray, 0, count);
3462                 }
3463                 array = newarray;
3464             }
3465             array[count++] = value;
3466         }
3467 
3468         void setElementAt(int value, int index) {
3469             array[index] = value;
3470         }
3471     }
3472 
3473     @SuppressWarnings("serial")
3474     static class KeyboardState implements Serializable {
3475         private static final Object keyCodesKey =
3476             JComponent.KeyboardState.class;
3477 
3478         // Get the array of key codes from the AppContext.
3479         static IntVector getKeyCodeArray() {
3480             IntVector iv =
3481                 (IntVector)SwingUtilities.appContextGet(keyCodesKey);
3482             if (iv == null) {
3483                 iv = new IntVector();
3484                 SwingUtilities.appContextPut(keyCodesKey, iv);
3485             }
3486             return iv;
3487         }
3488 
3489         static void registerKeyPressed(int keyCode) {
3490             IntVector kca = getKeyCodeArray();
3491             int count = kca.size();
3492             int i;
3493             for(i=0;i<count;i++) {
3494                 if(kca.elementAt(i) == -1){
3495                     kca.setElementAt(keyCode, i);
3496                     return;
3497                 }
3498             }
3499             kca.addElement(keyCode);
3500         }
3501 
3502         static void registerKeyReleased(int keyCode) {
3503             IntVector kca = getKeyCodeArray();
3504             int count = kca.size();
3505             int i;
3506             for(i=0;i<count;i++) {
3507                 if(kca.elementAt(i) == keyCode) {
3508                     kca.setElementAt(-1, i);
3509                     return;
3510                 }
3511             }
3512         }
3513 
3514         static boolean keyIsPressed(int keyCode) {
3515             IntVector kca = getKeyCodeArray();
3516             int count = kca.size();
3517             int i;
3518             for(i=0;i<count;i++) {
3519                 if(kca.elementAt(i) == keyCode) {
3520                     return true;
3521                 }
3522             }
3523             return false;
3524         }
3525 
3526         /**
3527          * Updates internal state of the KeyboardState and returns true
3528          * if the event should be processed further.
3529          */
3530         static boolean shouldProcess(KeyEvent e) {
3531             switch (e.getID()) {
3532             case KeyEvent.KEY_PRESSED:
3533                 if (!keyIsPressed(e.getKeyCode())) {
3534                     registerKeyPressed(e.getKeyCode());
3535                 }
3536                 return true;
3537             case KeyEvent.KEY_RELEASED:
3538                 // We are forced to process VK_PRINTSCREEN separately because
3539                 // the Windows doesn't generate the key pressed event for
3540                 // printscreen and it block the processing of key release
3541                 // event for printscreen.
3542                 if (keyIsPressed(e.getKeyCode()) || e.getKeyCode()==KeyEvent.VK_PRINTSCREEN) {
3543                     registerKeyReleased(e.getKeyCode());
3544                     return true;
3545                 }
3546                 return false;
3547             case KeyEvent.KEY_TYPED:
3548                 return true;
3549             default:
3550                 // Not a known KeyEvent type, bail.
3551                 return false;
3552             }
3553       }
3554     }
3555 
3556     static final sun.awt.RequestFocusController focusController =
3557         new sun.awt.RequestFocusController() {
3558             public boolean acceptRequestFocus(Component from, Component to,
3559                                               boolean temporary, boolean focusedWindowChangeAllowed,
3560                                               sun.awt.CausedFocusEvent.Cause cause)
3561             {
3562                 if ((to == null) || !(to instanceof JComponent)) {
3563                     return true;
3564                 }
3565 
3566                 if ((from == null) || !(from instanceof JComponent)) {
3567                     return true;
3568                 }
3569 
3570                 JComponent target = (JComponent) to;
3571                 if (!target.getVerifyInputWhenFocusTarget()) {
3572                     return true;
3573                 }
3574 
3575                 JComponent jFocusOwner = (JComponent)from;
3576                 InputVerifier iv = jFocusOwner.getInputVerifier();
3577 
3578                 if (iv == null) {
3579                     return true;
3580                 } else {
3581                     Object currentSource = SwingUtilities.appContextGet(
3582                             INPUT_VERIFIER_SOURCE_KEY);
3583                     if (currentSource == jFocusOwner) {
3584                         // We're currently calling into the InputVerifier
3585                         // for this component, so allow the focus change.
3586                         return true;
3587                     }
3588                     SwingUtilities.appContextPut(INPUT_VERIFIER_SOURCE_KEY,
3589                                                  jFocusOwner);
3590                     try {
3591                         return iv.shouldYieldFocus(jFocusOwner);
3592                     } finally {
3593                         if (currentSource != null) {
3594                             // We're already in the InputVerifier for
3595                             // currentSource. By resetting the currentSource
3596                             // we ensure that if the InputVerifier for
3597                             // currentSource does a requestFocus, we don't
3598                             // try and run the InputVerifier again.
3599                             SwingUtilities.appContextPut(
3600                                 INPUT_VERIFIER_SOURCE_KEY, currentSource);
3601                         } else {
3602                             SwingUtilities.appContextRemove(
3603                                 INPUT_VERIFIER_SOURCE_KEY);
3604                         }
3605                     }
3606                 }
3607             }
3608         };
3609 
3610     /*
3611      * --- Accessibility Support ---
3612      */
3613 
3614     /**
3615      * @deprecated As of JDK version 1.1,
3616      * replaced by <code>java.awt.Component.setEnabled(boolean)</code>.
3617      */
3618     @Deprecated
3619     public void enable() {
3620         if (isEnabled() != true) {
3621             super.enable();
3622             if (accessibleContext != null) {
3623                 accessibleContext.firePropertyChange(
3624                     AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
3625                     null, AccessibleState.ENABLED);
3626             }
3627         }
3628     }
3629 
3630     /**
3631      * @deprecated As of JDK version 1.1,
3632      * replaced by <code>java.awt.Component.setEnabled(boolean)</code>.
3633      */
3634     @Deprecated
3635     public void disable() {
3636         if (isEnabled() != false) {
3637             super.disable();
3638             if (accessibleContext != null) {
3639                 accessibleContext.firePropertyChange(
3640                     AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
3641                     AccessibleState.ENABLED, null);
3642             }
3643         }
3644     }
3645 
3646     /**
3647      * Inner class of JComponent used to provide default support for
3648      * accessibility.  This class is not meant to be used directly by
3649      * application developers, but is instead meant only to be
3650      * subclassed by component developers.
3651      * <p>
3652      * <strong>Warning:</strong>
3653      * Serialized objects of this class will not be compatible with
3654      * future Swing releases. The current serialization support is
3655      * appropriate for short term storage or RMI between applications running
3656      * the same version of Swing.  As of 1.4, support for long term storage
3657      * of all JavaBeans&trade;
3658      * has been added to the <code>java.beans</code> package.
3659      * Please see {@link java.beans.XMLEncoder}.
3660      */
3661     @SuppressWarnings("serial") // Same-version serialization only
3662     public abstract class AccessibleJComponent extends AccessibleAWTContainer
3663        implements AccessibleExtendedComponent
3664     {
3665         /**
3666          * Though the class is abstract, this should be called by
3667          * all sub-classes.
3668          */
3669         protected AccessibleJComponent() {
3670             super();
3671         }
3672 
3673         /**
3674          * Number of PropertyChangeListener objects registered. It's used
3675          * to add/remove ContainerListener and FocusListener to track
3676          * target JComponent's state
3677          */
3678         private volatile transient int propertyListenersCount = 0;
3679 
3680         /**
3681          * This field duplicates the function of the accessibleAWTFocusHandler field
3682          * in java.awt.Component.AccessibleAWTComponent, so it has been deprecated.
3683          */
3684         @Deprecated
3685         protected FocusListener accessibleFocusHandler = null;
3686 
3687         /**
3688          * Fire PropertyChange listener, if one is registered,
3689          * when children added/removed.
3690          */
3691         protected class AccessibleContainerHandler
3692             implements ContainerListener {
3693             public void componentAdded(ContainerEvent e) {
3694                 Component c = e.getChild();
3695                 if (c != null && c instanceof Accessible) {
3696                     AccessibleJComponent.this.firePropertyChange(
3697                         AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
3698                         null, c.getAccessibleContext());
3699                 }
3700             }
3701             public void componentRemoved(ContainerEvent e) {
3702                 Component c = e.getChild();
3703                 if (c != null && c instanceof Accessible) {
3704                     AccessibleJComponent.this.firePropertyChange(
3705                         AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
3706                         c.getAccessibleContext(), null);
3707                 }
3708             }
3709         }
3710 
3711         /**
3712          * Fire PropertyChange listener, if one is registered,
3713          * when focus events happen
3714          * @since 1.3
3715          */
3716         protected class AccessibleFocusHandler implements FocusListener {
3717            public void focusGained(FocusEvent event) {
3718                if (accessibleContext != null) {
3719                     accessibleContext.firePropertyChange(
3720                         AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
3721                         null, AccessibleState.FOCUSED);
3722                 }
3723             }
3724             public void focusLost(FocusEvent event) {
3725                 if (accessibleContext != null) {
3726                     accessibleContext.firePropertyChange(
3727                         AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
3728                         AccessibleState.FOCUSED, null);
3729                 }
3730             }
3731         } // inner class AccessibleFocusHandler
3732 
3733 
3734         /**
3735          * Adds a PropertyChangeListener to the listener list.
3736          *
3737          * @param listener  the PropertyChangeListener to be added
3738          */
3739         public void addPropertyChangeListener(PropertyChangeListener listener) {
3740             // Due to JDK-7179482 the accessibleFocusHandler field in this class
3741             // is deprecated and need to use accessibleAWTFocusHandler in superclass.
3742             if (accessibleAWTFocusHandler == null) {
3743                 accessibleAWTFocusHandler = new AccessibleFocusHandler();
3744             }
3745             if (accessibleContainerHandler == null) {
3746                 accessibleContainerHandler = new AccessibleContainerHandler();
3747             }
3748             if (propertyListenersCount++ == 0) {
3749                 JComponent.this.addFocusListener(accessibleAWTFocusHandler);
3750                 JComponent.this.addContainerListener(accessibleContainerHandler);
3751             }
3752             super.addPropertyChangeListener(listener);
3753         }
3754 
3755         /**
3756          * Removes a PropertyChangeListener from the listener list.
3757          * This removes a PropertyChangeListener that was registered
3758          * for all properties.
3759          *
3760          * @param listener  the PropertyChangeListener to be removed
3761          */
3762         public void removePropertyChangeListener(PropertyChangeListener listener) {
3763             if (--propertyListenersCount == 0) {
3764                 // Due to JDK-7179482 the accessibleFocusHandler field in this class
3765                 // is deprecated and need to use accessibleAWTFocusHandler in superclass.
3766                 JComponent.this.removeFocusListener(accessibleAWTFocusHandler);
3767                 JComponent.this.removeContainerListener(accessibleContainerHandler);
3768             }
3769             super.removePropertyChangeListener(listener);
3770         }
3771 
3772 
3773 
3774         /**
3775          * Recursively search through the border hierarchy (if it exists)
3776          * for a TitledBorder with a non-null title.  This does a depth
3777          * first search on first the inside borders then the outside borders.
3778          * The assumption is that titles make really pretty inside borders
3779          * but not very pretty outside borders in compound border situations.
3780          * It's rather arbitrary, but hopefully decent UI programmers will
3781          * not create multiple titled borders for the same component.
3782          */
3783         protected String getBorderTitle(Border b) {
3784             String s;
3785             if (b instanceof TitledBorder) {
3786                 return ((TitledBorder) b).getTitle();
3787             } else if (b instanceof CompoundBorder) {
3788                 s = getBorderTitle(((CompoundBorder) b).getInsideBorder());
3789                 if (s == null) {
3790                     s = getBorderTitle(((CompoundBorder) b).getOutsideBorder());
3791                 }
3792                 return s;
3793             } else {
3794                 return null;
3795             }
3796         }
3797 
3798         // AccessibleContext methods
3799         //
3800         /**
3801          * Gets the accessible name of this object.  This should almost never
3802          * return java.awt.Component.getName(), as that generally isn't
3803          * a localized name, and doesn't have meaning for the user.  If the
3804          * object is fundamentally a text object (such as a menu item), the
3805          * accessible name should be the text of the object (for example,
3806          * "save").
3807          * If the object has a tooltip, the tooltip text may also be an
3808          * appropriate String to return.
3809          *
3810          * @return the localized name of the object -- can be null if this
3811          *         object does not have a name
3812          * @see AccessibleContext#setAccessibleName
3813          */
3814         public String getAccessibleName() {
3815             String name = accessibleName;
3816 
3817             // fallback to the client name property
3818             //
3819             if (name == null) {
3820                 name = (String)getClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY);
3821             }
3822 
3823             // fallback to the titled border if it exists
3824             //
3825             if (name == null) {
3826                 name = getBorderTitle(getBorder());
3827             }
3828 
3829             // fallback to the label labeling us if it exists
3830             //
3831             if (name == null) {
3832                 Object o = getClientProperty(JLabel.LABELED_BY_PROPERTY);
3833                 if (o instanceof Accessible) {
3834                     AccessibleContext ac = ((Accessible) o).getAccessibleContext();
3835                     if (ac != null) {
3836                         name = ac.getAccessibleName();
3837                     }
3838                 }
3839             }
3840             return name;
3841         }
3842 
3843         /**
3844          * Gets the accessible description of this object.  This should be
3845          * a concise, localized description of what this object is - what
3846          * is its meaning to the user.  If the object has a tooltip, the
3847          * tooltip text may be an appropriate string to return, assuming
3848          * it contains a concise description of the object (instead of just
3849          * the name of the object - for example a "Save" icon on a toolbar that
3850          * had "save" as the tooltip text shouldn't return the tooltip
3851          * text as the description, but something like "Saves the current
3852          * text document" instead).
3853          *
3854          * @return the localized description of the object -- can be null if
3855          * this object does not have a description
3856          * @see AccessibleContext#setAccessibleDescription
3857          */
3858         public String getAccessibleDescription() {
3859             String description = accessibleDescription;
3860 
3861             // fallback to the client description property
3862             //
3863             if (description == null) {
3864                 description = (String)getClientProperty(AccessibleContext.ACCESSIBLE_DESCRIPTION_PROPERTY);
3865             }
3866 
3867             // fallback to the tool tip text if it exists
3868             //
3869             if (description == null) {
3870                 try {
3871                     description = getToolTipText();
3872                 } catch (Exception e) {
3873                     // Just in case the subclass overrode the
3874                     // getToolTipText method and actually
3875                     // requires a MouseEvent.
3876                     // [[[FIXME:  WDW - we probably should require this
3877                     // method to take a MouseEvent and just pass it on
3878                     // to getToolTipText.  The swing-feedback traffic
3879                     // leads me to believe getToolTipText might change,
3880                     // though, so I was hesitant to make this change at
3881                     // this time.]]]
3882                 }
3883             }
3884 
3885             // fallback to the label labeling us if it exists
3886             //
3887             if (description == null) {
3888                 Object o = getClientProperty(JLabel.LABELED_BY_PROPERTY);
3889                 if (o instanceof Accessible) {
3890                     AccessibleContext ac = ((Accessible) o).getAccessibleContext();
3891                     if (ac != null) {
3892                         description = ac.getAccessibleDescription();
3893                     }
3894                 }
3895             }
3896 
3897             return description;
3898         }
3899 
3900         /**
3901          * Gets the role of this object.
3902          *
3903          * @return an instance of AccessibleRole describing the role of the
3904          * object
3905          * @see AccessibleRole
3906          */
3907         public AccessibleRole getAccessibleRole() {
3908             return AccessibleRole.SWING_COMPONENT;
3909         }
3910 
3911         /**
3912          * Gets the state of this object.
3913          *
3914          * @return an instance of AccessibleStateSet containing the current
3915          * state set of the object
3916          * @see AccessibleState
3917          */
3918         public AccessibleStateSet getAccessibleStateSet() {
3919             AccessibleStateSet states = super.getAccessibleStateSet();
3920             if (JComponent.this.isOpaque()) {
3921                 states.add(AccessibleState.OPAQUE);
3922             }
3923             return states;
3924         }
3925 
3926         /**
3927          * Returns the number of accessible children in the object.  If all
3928          * of the children of this object implement Accessible, than this
3929          * method should return the number of children of this object.
3930          *
3931          * @return the number of accessible children in the object.
3932          */
3933         public int getAccessibleChildrenCount() {
3934             return super.getAccessibleChildrenCount();
3935         }
3936 
3937         /**
3938          * Returns the nth Accessible child of the object.
3939          *
3940          * @param i zero-based index of child
3941          * @return the nth Accessible child of the object
3942          */
3943         public Accessible getAccessibleChild(int i) {
3944             return super.getAccessibleChild(i);
3945         }
3946 
3947         // ----- AccessibleExtendedComponent
3948 
3949         /**
3950          * Returns the AccessibleExtendedComponent
3951          *
3952          * @return the AccessibleExtendedComponent
3953          */
3954         AccessibleExtendedComponent getAccessibleExtendedComponent() {
3955             return this;
3956         }
3957 
3958         /**
3959          * Returns the tool tip text
3960          *
3961          * @return the tool tip text, if supported, of the object;
3962          * otherwise, null
3963          * @since 1.4
3964          */
3965         public String getToolTipText() {
3966             return JComponent.this.getToolTipText();
3967         }
3968 
3969         /**
3970          * Returns the titled border text
3971          *
3972          * @return the titled border text, if supported, of the object;
3973          * otherwise, null
3974          * @since 1.4
3975          */
3976         public String getTitledBorderText() {
3977             Border border = JComponent.this.getBorder();
3978             if (border instanceof TitledBorder) {
3979                 return ((TitledBorder)border).getTitle();
3980             } else {
3981                 return null;
3982             }
3983         }
3984 
3985         /**
3986          * Returns key bindings associated with this object
3987          *
3988          * @return the key bindings, if supported, of the object;
3989          * otherwise, null
3990          * @see AccessibleKeyBinding
3991          * @since 1.4
3992          */
3993         public AccessibleKeyBinding getAccessibleKeyBinding() {
3994             return null;
3995         }
3996     } // inner class AccessibleJComponent
3997 
3998 
3999     /**
4000      * Returns an <code>ArrayTable</code> used for
4001      * key/value "client properties" for this component. If the
4002      * <code>clientProperties</code> table doesn't exist, an empty one
4003      * will be created.
4004      *
4005      * @return an ArrayTable
4006      * @see #putClientProperty
4007      * @see #getClientProperty
4008      */
4009     private ArrayTable getClientProperties() {
4010         if (clientProperties == null) {
4011             clientProperties = new ArrayTable();
4012         }
4013         return clientProperties;
4014     }
4015 
4016 
4017     /**
4018      * Returns the value of the property with the specified key.  Only
4019      * properties added with <code>putClientProperty</code> will return
4020      * a non-<code>null</code> value.
4021      *
4022      * @param key the being queried
4023      * @return the value of this property or <code>null</code>
4024      * @see #putClientProperty
4025      */
4026     public final Object getClientProperty(Object key) {
4027         if (key == SwingUtilities2.AA_TEXT_PROPERTY_KEY) {
4028             return aaTextInfo;
4029         } else if (key == SwingUtilities2.COMPONENT_UI_PROPERTY_KEY) {
4030             return ui;
4031         }
4032          if(clientProperties == null) {
4033             return null;
4034         } else {
4035             synchronized(clientProperties) {
4036                 return clientProperties.get(key);
4037             }
4038         }
4039     }
4040 
4041     /**
4042      * Adds an arbitrary key/value "client property" to this component.
4043      * <p>
4044      * The <code>get/putClientProperty</code> methods provide access to
4045      * a small per-instance hashtable. Callers can use get/putClientProperty
4046      * to annotate components that were created by another module.
4047      * For example, a
4048      * layout manager might store per child constraints this way. For example:
4049      * <pre>
4050      * componentA.putClientProperty("to the left of", componentB);
4051      * </pre>
4052      * If value is <code>null</code> this method will remove the property.
4053      * Changes to client properties are reported with
4054      * <code>PropertyChange</code> events.
4055      * The name of the property (for the sake of PropertyChange
4056      * events) is <code>key.toString()</code>.
4057      * <p>
4058      * The <code>clientProperty</code> dictionary is not intended to
4059      * support large
4060      * scale extensions to JComponent nor should be it considered an
4061      * alternative to subclassing when designing a new component.
4062      *
4063      * @param key the new client property key
4064      * @param value the new client property value; if <code>null</code>
4065      *          this method will remove the property
4066      * @see #getClientProperty
4067      * @see #addPropertyChangeListener
4068      */
4069     public final void putClientProperty(Object key, Object value) {
4070         if (key == SwingUtilities2.AA_TEXT_PROPERTY_KEY) {
4071             aaTextInfo = value;
4072             return;
4073         }
4074         if (value == null && clientProperties == null) {
4075             // Both the value and ArrayTable are null, implying we don't
4076             // have to do anything.
4077             return;
4078         }
4079         ArrayTable clientProperties = getClientProperties();
4080         Object oldValue;
4081         synchronized(clientProperties) {
4082             oldValue = clientProperties.get(key);
4083             if (value != null) {
4084                 clientProperties.put(key, value);
4085             } else if (oldValue != null) {
4086                 clientProperties.remove(key);
4087             } else {
4088                 // old == new == null
4089                 return;
4090             }
4091         }
4092         clientPropertyChanged(key, oldValue, value);
4093         firePropertyChange(key.toString(), oldValue, value);
4094     }
4095 
4096     // Invoked from putClientProperty.  This is provided for subclasses
4097     // in Swing.
4098     void clientPropertyChanged(Object key, Object oldValue,
4099                                Object newValue) {
4100     }
4101 
4102 
4103     /*
4104      * Sets the property with the specified name to the specified value if
4105      * the property has not already been set by the client program.
4106      * This method is used primarily to set UI defaults for properties
4107      * with primitive types, where the values cannot be marked with
4108      * UIResource.
4109      * @see LookAndFeel#installProperty
4110      * @param propertyName String containing the name of the property
4111      * @param value Object containing the property value
4112      */
4113     void setUIProperty(String propertyName, Object value) {
4114         if (propertyName == "opaque") {
4115             if (!getFlag(OPAQUE_SET)) {
4116                 setOpaque(((Boolean)value).booleanValue());
4117                 setFlag(OPAQUE_SET, false);
4118             }
4119         } else if (propertyName == "autoscrolls") {
4120             if (!getFlag(AUTOSCROLLS_SET)) {
4121                 setAutoscrolls(((Boolean)value).booleanValue());
4122                 setFlag(AUTOSCROLLS_SET, false);
4123             }
4124         } else if (propertyName == "focusTraversalKeysForward") {
4125             if (!getFlag(FOCUS_TRAVERSAL_KEYS_FORWARD_SET)) {
4126                 super.setFocusTraversalKeys(KeyboardFocusManager.
4127                                             FORWARD_TRAVERSAL_KEYS,
4128                                             (Set<AWTKeyStroke>)value);
4129             }
4130         } else if (propertyName == "focusTraversalKeysBackward") {
4131             if (!getFlag(FOCUS_TRAVERSAL_KEYS_BACKWARD_SET)) {
4132                 super.setFocusTraversalKeys(KeyboardFocusManager.
4133                                             BACKWARD_TRAVERSAL_KEYS,
4134                                             (Set<AWTKeyStroke>)value);
4135             }
4136         } else {
4137             throw new IllegalArgumentException("property \""+
4138                                                propertyName+ "\" cannot be set using this method");
4139         }
4140     }
4141 
4142 
4143     /**
4144      * Sets the focus traversal keys for a given traversal operation for this
4145      * Component.
4146      * Refer to
4147      * {@link java.awt.Component#setFocusTraversalKeys}
4148      * for a complete description of this method.
4149      * <p>
4150      * This method may throw a {@code ClassCastException} if any {@code Object}
4151      * in {@code keystrokes} is not an {@code AWTKeyStroke}.
4152      *
4153      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
4154      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
4155      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
4156      * @param keystrokes the Set of AWTKeyStroke for the specified operation
4157      * @see java.awt.KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
4158      * @see java.awt.KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
4159      * @see java.awt.KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
4160      * @throws IllegalArgumentException if id is not one of
4161      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
4162      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
4163      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or if keystrokes
4164      *         contains null, or if any keystroke represents a KEY_TYPED event,
4165      *         or if any keystroke already maps to another focus traversal
4166      *         operation for this Component
4167      * @since 1.5
4168      * @beaninfo
4169      *       bound: true
4170      */
4171     public void
4172         setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes)
4173     {
4174         if (id == KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS) {
4175             setFlag(FOCUS_TRAVERSAL_KEYS_FORWARD_SET,true);
4176         } else if (id == KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS) {
4177             setFlag(FOCUS_TRAVERSAL_KEYS_BACKWARD_SET,true);
4178         }
4179         super.setFocusTraversalKeys(id,keystrokes);
4180     }
4181 
4182     /* --- Transitional java.awt.Component Support ---
4183      * The methods and fields in this section will migrate to
4184      * java.awt.Component in the next JDK release.
4185      */
4186 
4187     /**
4188      * Returns true if this component is lightweight, that is, if it doesn't
4189      * have a native window system peer.
4190      *
4191      * @return true if this component is lightweight
4192      */
4193     @SuppressWarnings("deprecation")
4194     public static boolean isLightweightComponent(Component c) {
4195         return c.getPeer() instanceof LightweightPeer;
4196     }
4197 
4198 
4199     /**
4200      * @deprecated As of JDK 5,
4201      * replaced by <code>Component.setBounds(int, int, int, int)</code>.
4202      * <p>
4203      * Moves and resizes this component.
4204      *
4205      * @param x  the new horizontal location
4206      * @param y  the new vertical location
4207      * @param w  the new width
4208      * @param h  the new height
4209      * @see java.awt.Component#setBounds
4210      */
4211     @Deprecated
4212     public void reshape(int x, int y, int w, int h) {
4213         super.reshape(x, y, w, h);
4214     }
4215 
4216 
4217     /**
4218      * Stores the bounds of this component into "return value"
4219      * <code>rv</code> and returns <code>rv</code>.
4220      * If <code>rv</code> is <code>null</code> a new <code>Rectangle</code>
4221      * is allocated.  This version of <code>getBounds</code> is useful
4222      * if the caller wants to avoid allocating a new <code>Rectangle</code>
4223      * object on the heap.
4224      *
4225      * @param rv the return value, modified to the component's bounds
4226      * @return <code>rv</code>; if <code>rv</code> is <code>null</code>
4227      *          return a newly created <code>Rectangle</code> with this
4228      *          component's bounds
4229      */
4230     public Rectangle getBounds(Rectangle rv) {
4231         if (rv == null) {
4232             return new Rectangle(getX(), getY(), getWidth(), getHeight());
4233         }
4234         else {
4235             rv.setBounds(getX(), getY(), getWidth(), getHeight());
4236             return rv;
4237         }
4238     }
4239 
4240 
4241     /**
4242      * Stores the width/height of this component into "return value"
4243      * <code>rv</code> and returns <code>rv</code>.
4244      * If <code>rv</code> is <code>null</code> a new <code>Dimension</code>
4245      * object is allocated.  This version of <code>getSize</code>
4246      * is useful if the caller wants to avoid allocating a new
4247      * <code>Dimension</code> object on the heap.
4248      *
4249      * @param rv the return value, modified to the component's size
4250      * @return <code>rv</code>
4251      */
4252     public Dimension getSize(Dimension rv) {
4253         if (rv == null) {
4254             return new Dimension(getWidth(), getHeight());
4255         }
4256         else {
4257             rv.setSize(getWidth(), getHeight());
4258             return rv;
4259         }
4260     }
4261 
4262 
4263     /**
4264      * Stores the x,y origin of this component into "return value"
4265      * <code>rv</code> and returns <code>rv</code>.
4266      * If <code>rv</code> is <code>null</code> a new <code>Point</code>
4267      * is allocated.  This version of <code>getLocation</code> is useful
4268      * if the caller wants to avoid allocating a new <code>Point</code>
4269      * object on the heap.
4270      *
4271      * @param rv the return value, modified to the component's location
4272      * @return <code>rv</code>
4273      */
4274     public Point getLocation(Point rv) {
4275         if (rv == null) {
4276             return new Point(getX(), getY());
4277         }
4278         else {
4279             rv.setLocation(getX(), getY());
4280             return rv;
4281         }
4282     }
4283 
4284 
4285     /**
4286      * Returns the current x coordinate of the component's origin.
4287      * This method is preferable to writing
4288      * <code>component.getBounds().x</code>, or
4289      * <code>component.getLocation().x</code> because it doesn't cause any
4290      * heap allocations.
4291      *
4292      * @return the current x coordinate of the component's origin
4293      */
4294     public int getX() { return super.getX(); }
4295 
4296 
4297     /**
4298      * Returns the current y coordinate of the component's origin.
4299      * This method is preferable to writing
4300      * <code>component.getBounds().y</code>, or
4301      * <code>component.getLocation().y</code> because it doesn't cause any
4302      * heap allocations.
4303      *
4304      * @return the current y coordinate of the component's origin
4305      */
4306     public int getY() { return super.getY(); }
4307 
4308 
4309     /**
4310      * Returns the current width of this component.
4311      * This method is preferable to writing
4312      * <code>component.getBounds().width</code>, or
4313      * <code>component.getSize().width</code> because it doesn't cause any
4314      * heap allocations.
4315      *
4316      * @return the current width of this component
4317      */
4318     public int getWidth() { return super.getWidth(); }
4319 
4320 
4321     /**
4322      * Returns the current height of this component.
4323      * This method is preferable to writing
4324      * <code>component.getBounds().height</code>, or
4325      * <code>component.getSize().height</code> because it doesn't cause any
4326      * heap allocations.
4327      *
4328      * @return the current height of this component
4329      */
4330     public int getHeight() { return super.getHeight(); }
4331 
4332     /**
4333      * Returns true if this component is completely opaque.
4334      * <p>
4335      * An opaque component paints every pixel within its
4336      * rectangular bounds. A non-opaque component paints only a subset of
4337      * its pixels or none at all, allowing the pixels underneath it to
4338      * "show through".  Therefore, a component that does not fully paint
4339      * its pixels provides a degree of transparency.
4340      * <p>
4341      * Subclasses that guarantee to always completely paint their contents
4342      * should override this method and return true.
4343      *
4344      * @return true if this component is completely opaque
4345      * @see #setOpaque
4346      */
4347     public boolean isOpaque() {
4348         return getFlag(IS_OPAQUE);
4349     }
4350 
4351     /**
4352      * If true the component paints every pixel within its bounds.
4353      * Otherwise, the component may not paint some or all of its
4354      * pixels, allowing the underlying pixels to show through.
4355      * <p>
4356      * The default value of this property is false for <code>JComponent</code>.
4357      * However, the default value for this property on most standard
4358      * <code>JComponent</code> subclasses (such as <code>JButton</code> and
4359      * <code>JTree</code>) is look-and-feel dependent.
4360      *
4361      * @param isOpaque  true if this component should be opaque
4362      * @see #isOpaque
4363      * @beaninfo
4364      *        bound: true
4365      *       expert: true
4366      *  description: The component's opacity
4367      */
4368     public void setOpaque(boolean isOpaque) {
4369         boolean oldValue = getFlag(IS_OPAQUE);
4370         setFlag(IS_OPAQUE, isOpaque);
4371         setFlag(OPAQUE_SET, true);
4372         firePropertyChange("opaque", oldValue, isOpaque);
4373     }
4374 
4375 
4376     /**
4377      * If the specified rectangle is completely obscured by any of this
4378      * component's opaque children then returns true.  Only direct children
4379      * are considered, more distant descendants are ignored.  A
4380      * <code>JComponent</code> is opaque if
4381      * <code>JComponent.isOpaque()</code> returns true, other lightweight
4382      * components are always considered transparent, and heavyweight components
4383      * are always considered opaque.
4384      *
4385      * @param x  x value of specified rectangle
4386      * @param y  y value of specified rectangle
4387      * @param width  width of specified rectangle
4388      * @param height height of specified rectangle
4389      * @return true if the specified rectangle is obscured by an opaque child
4390      */
4391     boolean rectangleIsObscured(int x,int y,int width,int height)
4392     {
4393         int numChildren = getComponentCount();
4394 
4395         for(int i = 0; i < numChildren; i++) {
4396             Component child = getComponent(i);
4397             int cx, cy, cw, ch;
4398 
4399             cx = child.getX();
4400             cy = child.getY();
4401             cw = child.getWidth();
4402             ch = child.getHeight();
4403 
4404             if (x >= cx && (x + width) <= (cx + cw) &&
4405                 y >= cy && (y + height) <= (cy + ch) && child.isVisible()) {
4406 
4407                 if(child instanceof JComponent) {
4408 //                  System.out.println("A) checking opaque: " + ((JComponent)child).isOpaque() + "  " + child);
4409 //                  System.out.print("B) ");
4410 //                  Thread.dumpStack();
4411                     return child.isOpaque();
4412                 } else {
4413                     /** Sometimes a heavy weight can have a bound larger than its peer size
4414                      *  so we should always draw under heavy weights
4415                      */
4416                     return false;
4417                 }
4418             }
4419         }
4420 
4421         return false;
4422     }
4423 
4424 
4425     /**
4426      * Returns the <code>Component</code>'s "visible rect rectangle" -  the
4427      * intersection of the visible rectangles for the component <code>c</code>
4428      * and all of its ancestors.  The return value is stored in
4429      * <code>visibleRect</code>.
4430      *
4431      * @param c  the component
4432      * @param visibleRect  a <code>Rectangle</code> computed as the
4433      *          intersection of all visible rectangles for the component
4434      *          <code>c</code> and all of its ancestors -- this is the
4435      *          return value for this method
4436      * @see #getVisibleRect
4437      */
4438     static final void computeVisibleRect(Component c, Rectangle visibleRect) {
4439         Container p = c.getParent();
4440         Rectangle bounds = c.getBounds();
4441 
4442         if (p == null || p instanceof Window || p instanceof Applet) {
4443             visibleRect.setBounds(0, 0, bounds.width, bounds.height);
4444         } else {
4445             computeVisibleRect(p, visibleRect);
4446             visibleRect.x -= bounds.x;
4447             visibleRect.y -= bounds.y;
4448             SwingUtilities.computeIntersection(0,0,bounds.width,bounds.height,visibleRect);
4449         }
4450     }
4451 
4452 
4453     /**
4454      * Returns the <code>Component</code>'s "visible rect rectangle" -  the
4455      * intersection of the visible rectangles for this component
4456      * and all of its ancestors.  The return value is stored in
4457      * <code>visibleRect</code>.
4458      *
4459      * @param visibleRect a <code>Rectangle</code> computed as the
4460      *          intersection of all visible rectangles for this
4461      *          component and all of its ancestors -- this is the return
4462      *          value for this method
4463      * @see #getVisibleRect
4464      */
4465     public void computeVisibleRect(Rectangle visibleRect) {
4466         computeVisibleRect(this, visibleRect);
4467     }
4468 
4469 
4470     /**
4471      * Returns the <code>Component</code>'s "visible rectangle" -  the
4472      * intersection of this component's visible rectangle,
4473      * <code>new Rectangle(0, 0, getWidth(), getHeight())</code>,
4474      * and all of its ancestors' visible rectangles.
4475      *
4476      * @return the visible rectangle
4477      */
4478     public Rectangle getVisibleRect() {
4479         Rectangle visibleRect = new Rectangle();
4480 
4481         computeVisibleRect(visibleRect);
4482         return visibleRect;
4483     }
4484 
4485     /**
4486      * Support for reporting bound property changes for boolean properties.
4487      * This method can be called when a bound property has changed and it will
4488      * send the appropriate PropertyChangeEvent to any registered
4489      * PropertyChangeListeners.
4490      *
4491      * @param propertyName the property whose value has changed
4492      * @param oldValue the property's previous value
4493      * @param newValue the property's new value
4494      */
4495     public void firePropertyChange(String propertyName,
4496                                    boolean oldValue, boolean newValue) {
4497         super.firePropertyChange(propertyName, oldValue, newValue);
4498     }
4499 
4500 
4501     /**
4502      * Support for reporting bound property changes for integer properties.
4503      * This method can be called when a bound property has changed and it will
4504      * send the appropriate PropertyChangeEvent to any registered
4505      * PropertyChangeListeners.
4506      *
4507      * @param propertyName the property whose value has changed
4508      * @param oldValue the property's previous value
4509      * @param newValue the property's new value
4510      */
4511     public void firePropertyChange(String propertyName,
4512                                       int oldValue, int newValue) {
4513         super.firePropertyChange(propertyName, oldValue, newValue);
4514     }
4515 
4516     // XXX This method is implemented as a workaround to a JLS issue with ambiguous
4517     // methods. This should be removed once 4758654 is resolved.
4518     public void firePropertyChange(String propertyName, char oldValue, char newValue) {
4519         super.firePropertyChange(propertyName, oldValue, newValue);
4520     }
4521 
4522     /**
4523      * Supports reporting constrained property changes.
4524      * This method can be called when a constrained property has changed
4525      * and it will send the appropriate <code>PropertyChangeEvent</code>
4526      * to any registered <code>VetoableChangeListeners</code>.
4527      *
4528      * @param propertyName  the name of the property that was listened on
4529      * @param oldValue  the old value of the property
4530      * @param newValue  the new value of the property
4531      * @exception java.beans.PropertyVetoException when the attempt to set the
4532      *          property is vetoed by the component
4533      */
4534     protected void fireVetoableChange(String propertyName, Object oldValue, Object newValue)
4535         throws java.beans.PropertyVetoException
4536     {
4537         if (vetoableChangeSupport == null) {
4538             return;
4539         }
4540         vetoableChangeSupport.fireVetoableChange(propertyName, oldValue, newValue);
4541     }
4542 
4543 
4544     /**
4545      * Adds a <code>VetoableChangeListener</code> to the listener list.
4546      * The listener is registered for all properties.
4547      *
4548      * @param listener  the <code>VetoableChangeListener</code> to be added
4549      */
4550     public synchronized void addVetoableChangeListener(VetoableChangeListener listener) {
4551         if (vetoableChangeSupport == null) {
4552             vetoableChangeSupport = new java.beans.VetoableChangeSupport(this);
4553         }
4554         vetoableChangeSupport.addVetoableChangeListener(listener);
4555     }
4556 
4557 
4558     /**
4559      * Removes a <code>VetoableChangeListener</code> from the listener list.
4560      * This removes a <code>VetoableChangeListener</code> that was registered
4561      * for all properties.
4562      *
4563      * @param listener  the <code>VetoableChangeListener</code> to be removed
4564      */
4565     public synchronized void removeVetoableChangeListener(VetoableChangeListener listener) {
4566         if (vetoableChangeSupport == null) {
4567             return;
4568         }
4569         vetoableChangeSupport.removeVetoableChangeListener(listener);
4570     }
4571 
4572 
4573     /**
4574      * Returns an array of all the vetoable change listeners
4575      * registered on this component.
4576      *
4577      * @return all of the component's <code>VetoableChangeListener</code>s
4578      *         or an empty
4579      *         array if no vetoable change listeners are currently registered
4580      *
4581      * @see #addVetoableChangeListener
4582      * @see #removeVetoableChangeListener
4583      *
4584      * @since 1.4
4585      */
4586     public synchronized VetoableChangeListener[] getVetoableChangeListeners() {
4587         if (vetoableChangeSupport == null) {
4588             return new VetoableChangeListener[0];
4589         }
4590         return vetoableChangeSupport.getVetoableChangeListeners();
4591     }
4592 
4593 
4594     /**
4595      * Returns the top-level ancestor of this component (either the
4596      * containing <code>Window</code> or <code>Applet</code>),
4597      * or <code>null</code> if this component has not
4598      * been added to any container.
4599      *
4600      * @return the top-level <code>Container</code> that this component is in,
4601      *          or <code>null</code> if not in any container
4602      */
4603     public Container getTopLevelAncestor() {
4604         for(Container p = this; p != null; p = p.getParent()) {
4605             if(p instanceof Window || p instanceof Applet) {
4606                 return p;
4607             }
4608         }
4609         return null;
4610     }
4611 
4612     private AncestorNotifier getAncestorNotifier() {
4613         return (AncestorNotifier)
4614             getClientProperty(JComponent_ANCESTOR_NOTIFIER);
4615     }
4616 
4617     /**
4618      * Registers <code>listener</code> so that it will receive
4619      * <code>AncestorEvents</code> when it or any of its ancestors
4620      * move or are made visible or invisible.
4621      * Events are also sent when the component or its ancestors are added
4622      * or removed from the containment hierarchy.
4623      *
4624      * @param listener  the <code>AncestorListener</code> to register
4625      * @see AncestorEvent
4626      */
4627     public void addAncestorListener(AncestorListener listener) {
4628         AncestorNotifier ancestorNotifier = getAncestorNotifier();
4629         if (ancestorNotifier == null) {
4630             ancestorNotifier = new AncestorNotifier(this);
4631             putClientProperty(JComponent_ANCESTOR_NOTIFIER,
4632                               ancestorNotifier);
4633         }
4634         ancestorNotifier.addAncestorListener(listener);
4635     }
4636 
4637     /**
4638      * Unregisters <code>listener</code> so that it will no longer receive
4639      * <code>AncestorEvents</code>.
4640      *
4641      * @param listener  the <code>AncestorListener</code> to be removed
4642      * @see #addAncestorListener
4643      */
4644     public void removeAncestorListener(AncestorListener listener) {
4645         AncestorNotifier ancestorNotifier = getAncestorNotifier();
4646         if (ancestorNotifier == null) {
4647             return;
4648         }
4649         ancestorNotifier.removeAncestorListener(listener);
4650         if (ancestorNotifier.listenerList.getListenerList().length == 0) {
4651             ancestorNotifier.removeAllListeners();
4652             putClientProperty(JComponent_ANCESTOR_NOTIFIER, null);
4653         }
4654     }
4655 
4656     /**
4657      * Returns an array of all the ancestor listeners
4658      * registered on this component.
4659      *
4660      * @return all of the component's <code>AncestorListener</code>s
4661      *         or an empty
4662      *         array if no ancestor listeners are currently registered
4663      *
4664      * @see #addAncestorListener
4665      * @see #removeAncestorListener
4666      *
4667      * @since 1.4
4668      */
4669     public AncestorListener[] getAncestorListeners() {
4670         AncestorNotifier ancestorNotifier = getAncestorNotifier();
4671         if (ancestorNotifier == null) {
4672             return new AncestorListener[0];
4673         }
4674         return ancestorNotifier.getAncestorListeners();
4675     }
4676 
4677     /**
4678      * Returns an array of all the objects currently registered
4679      * as <code><em>Foo</em>Listener</code>s
4680      * upon this <code>JComponent</code>.
4681      * <code><em>Foo</em>Listener</code>s are registered using the
4682      * <code>add<em>Foo</em>Listener</code> method.
4683      *
4684      * <p>
4685      *
4686      * You can specify the <code>listenerType</code> argument
4687      * with a class literal,
4688      * such as
4689      * <code><em>Foo</em>Listener.class</code>.
4690      * For example, you can query a
4691      * <code>JComponent</code> <code>c</code>
4692      * for its mouse listeners with the following code:
4693      * <pre>MouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class));</pre>
4694      * If no such listeners exist, this method returns an empty array.
4695      *
4696      * @param listenerType the type of listeners requested; this parameter
4697      *          should specify an interface that descends from
4698      *          <code>java.util.EventListener</code>
4699      * @return an array of all objects registered as
4700      *          <code><em>Foo</em>Listener</code>s on this component,
4701      *          or an empty array if no such
4702      *          listeners have been added
4703      * @exception ClassCastException if <code>listenerType</code>
4704      *          doesn't specify a class or interface that implements
4705      *          <code>java.util.EventListener</code>
4706      *
4707      * @since 1.3
4708      *
4709      * @see #getVetoableChangeListeners
4710      * @see #getAncestorListeners
4711      */
4712     public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
4713         T[] result;
4714         if (listenerType == AncestorListener.class) {
4715             // AncestorListeners are handled by the AncestorNotifier
4716             result = (T[])getAncestorListeners();
4717         }
4718         else if (listenerType == VetoableChangeListener.class) {
4719             // VetoableChangeListeners are handled by VetoableChangeSupport
4720             result = (T[])getVetoableChangeListeners();
4721         }
4722         else if (listenerType == PropertyChangeListener.class) {
4723             // PropertyChangeListeners are handled by PropertyChangeSupport
4724             result = (T[])getPropertyChangeListeners();
4725         }
4726         else {
4727             result = listenerList.getListeners(listenerType);
4728         }
4729 
4730         if (result.length == 0) {
4731             return super.getListeners(listenerType);
4732         }
4733         return result;
4734     }
4735 
4736     /**
4737      * Notifies this component that it now has a parent component.
4738      * When this method is invoked, the chain of parent components is
4739      * set up with <code>KeyboardAction</code> event listeners.
4740      * This method is called by the toolkit internally and should
4741      * not be called directly by programs.
4742      *
4743      * @see #registerKeyboardAction
4744      */
4745     public void addNotify() {
4746         super.addNotify();
4747         firePropertyChange("ancestor", null, getParent());
4748 
4749         registerWithKeyboardManager(false);
4750         registerNextFocusableComponent();
4751     }
4752 
4753 
4754     /**
4755      * Notifies this component that it no longer has a parent component.
4756      * When this method is invoked, any <code>KeyboardAction</code>s
4757      * set up in the the chain of parent components are removed.
4758      * This method is called by the toolkit internally and should
4759      * not be called directly by programs.
4760      *
4761      * @see #registerKeyboardAction
4762      */
4763     public void removeNotify() {
4764         super.removeNotify();
4765         // This isn't strictly correct.  The event shouldn't be
4766         // fired until *after* the parent is set to null.  But
4767         // we only get notified before that happens
4768         firePropertyChange("ancestor", getParent(), null);
4769 
4770         unregisterWithKeyboardManager();
4771         deregisterNextFocusableComponent();
4772 
4773         if (getCreatedDoubleBuffer()) {
4774             RepaintManager.currentManager(this).resetDoubleBuffer();
4775             setCreatedDoubleBuffer(false);
4776         }
4777         if (autoscrolls) {
4778             Autoscroller.stop(this);
4779         }
4780     }
4781 
4782 
4783     /**
4784      * Adds the specified region to the dirty region list if the component
4785      * is showing.  The component will be repainted after all of the
4786      * currently pending events have been dispatched.
4787      *
4788      * @param tm  this parameter is not used
4789      * @param x  the x value of the dirty region
4790      * @param y  the y value of the dirty region
4791      * @param width  the width of the dirty region
4792      * @param height  the height of the dirty region
4793      * @see #isPaintingOrigin()
4794      * @see java.awt.Component#isShowing
4795      * @see RepaintManager#addDirtyRegion
4796      */
4797     public void repaint(long tm, int x, int y, int width, int height) {
4798         RepaintManager.currentManager(this).addDirtyRegion(this, x, y, width, height);
4799     }
4800 
4801 
4802     /**
4803      * Adds the specified region to the dirty region list if the component
4804      * is showing.  The component will be repainted after all of the
4805      * currently pending events have been dispatched.
4806      *
4807      * @param  r a <code>Rectangle</code> containing the dirty region
4808      * @see #isPaintingOrigin()
4809      * @see java.awt.Component#isShowing
4810      * @see RepaintManager#addDirtyRegion
4811      */
4812     public void repaint(Rectangle r) {
4813         repaint(0,r.x,r.y,r.width,r.height);
4814     }
4815 
4816 
4817     /**
4818      * Supports deferred automatic layout.
4819      * <p>
4820      * Calls <code>invalidate</code> and then adds this component's
4821      * <code>validateRoot</code> to a list of components that need to be
4822      * validated.  Validation will occur after all currently pending
4823      * events have been dispatched.  In other words after this method
4824      * is called,  the first validateRoot (if any) found when walking
4825      * up the containment hierarchy of this component will be validated.
4826      * By default, <code>JRootPane</code>, <code>JScrollPane</code>,
4827      * and <code>JTextField</code> return true
4828      * from <code>isValidateRoot</code>.
4829      * <p>
4830      * This method will automatically be called on this component
4831      * when a property value changes such that size, location, or
4832      * internal layout of this component has been affected.  This automatic
4833      * updating differs from the AWT because programs generally no
4834      * longer need to invoke <code>validate</code> to get the contents of the
4835      * GUI to update.
4836      *
4837      * @see java.awt.Component#invalidate
4838      * @see java.awt.Container#validate
4839      * @see #isValidateRoot
4840      * @see RepaintManager#addInvalidComponent
4841      */
4842     public void revalidate() {
4843         if (getParent() == null) {
4844             // Note: We don't bother invalidating here as once added
4845             // to a valid parent invalidate will be invoked (addImpl
4846             // invokes addNotify which will invoke invalidate on the
4847             // new Component). Also, if we do add a check to isValid
4848             // here it can potentially be called before the constructor
4849             // which was causing some people grief.
4850             return;
4851         }
4852         if (SwingUtilities.isEventDispatchThread()) {
4853             invalidate();
4854             RepaintManager.currentManager(this).addInvalidComponent(this);
4855         }
4856         else {
4857             // To avoid a flood of Runnables when constructing GUIs off
4858             // the EDT, a flag is maintained as to whether or not
4859             // a Runnable has been scheduled.
4860             synchronized(this) {
4861                 if (getFlag(REVALIDATE_RUNNABLE_SCHEDULED)) {
4862                     return;
4863                 }
4864                 setFlag(REVALIDATE_RUNNABLE_SCHEDULED, true);
4865             }
4866             Runnable callRevalidate = new Runnable() {
4867                 public void run() {
4868                     synchronized(JComponent.this) {
4869                         setFlag(REVALIDATE_RUNNABLE_SCHEDULED, false);
4870                     }
4871                     revalidate();
4872                 }
4873             };
4874             SwingUtilities.invokeLater(callRevalidate);
4875         }
4876     }
4877 
4878     /**
4879      * If this method returns true, <code>revalidate</code> calls by
4880      * descendants of this component will cause the entire tree
4881      * beginning with this root to be validated.
4882      * Returns false by default.  <code>JScrollPane</code> overrides
4883      * this method and returns true.
4884      *
4885      * @return always returns false
4886      * @see #revalidate
4887      * @see java.awt.Component#invalidate
4888      * @see java.awt.Container#validate
4889      * @see java.awt.Container#isValidateRoot
4890      */
4891     @Override
4892     public boolean isValidateRoot() {
4893         return false;
4894     }
4895 
4896 
4897     /**
4898      * Returns true if this component tiles its children -- that is, if
4899      * it can guarantee that the children will not overlap.  The
4900      * repainting system is substantially more efficient in this
4901      * common case.  <code>JComponent</code> subclasses that can't make this
4902      * guarantee, such as <code>JLayeredPane</code>,
4903      * should override this method to return false.
4904      *
4905      * @return always returns true
4906      */
4907     public boolean isOptimizedDrawingEnabled() {
4908         return true;
4909     }
4910 
4911     /**
4912      * Returns {@code true} if a paint triggered on a child component should cause
4913      * painting to originate from this Component, or one of its ancestors.
4914      * <p>
4915      * Calling {@link #repaint} or {@link #paintImmediately(int, int, int, int)}
4916      * on a Swing component will result in calling
4917      * the {@link JComponent#paintImmediately(int, int, int, int)} method of
4918      * the first ancestor which {@code isPaintingOrigin()} returns {@code true}, if there are any.
4919      * <p>
4920      * {@code JComponent} subclasses that need to be painted when any of their
4921      * children are repainted should override this method to return {@code true}.
4922      *
4923      * @return always returns {@code false}
4924      *
4925      * @see #paintImmediately(int, int, int, int)
4926      */
4927     protected boolean isPaintingOrigin() {
4928         return false;
4929     }
4930 
4931     /**
4932      * Paints the specified region in this component and all of its
4933      * descendants that overlap the region, immediately.
4934      * <p>
4935      * It's rarely necessary to call this method.  In most cases it's
4936      * more efficient to call repaint, which defers the actual painting
4937      * and can collapse redundant requests into a single paint call.
4938      * This method is useful if one needs to update the display while
4939      * the current event is being dispatched.
4940      * <p>
4941      * This method is to be overridden when the dirty region needs to be changed
4942      * for components that are painting origins.
4943      *
4944      * @param x  the x value of the region to be painted
4945      * @param y  the y value of the region to be painted
4946      * @param w  the width of the region to be painted
4947      * @param h  the height of the region to be painted
4948      * @see #repaint
4949      * @see #isPaintingOrigin()
4950      */
4951     public void paintImmediately(int x,int y,int w, int h) {
4952         Component c = this;
4953         Component parent;
4954 
4955         if(!isShowing()) {
4956             return;
4957         }
4958 
4959         JComponent paintingOigin = SwingUtilities.getPaintingOrigin(this);
4960         if (paintingOigin != null) {
4961             Rectangle rectangle = SwingUtilities.convertRectangle(
4962                     c, new Rectangle(x, y, w, h), paintingOigin);
4963             paintingOigin.paintImmediately(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
4964             return;
4965         }
4966 
4967         while(!c.isOpaque()) {
4968             parent = c.getParent();
4969             if(parent != null) {
4970                 x += c.getX();
4971                 y += c.getY();
4972                 c = parent;
4973             } else {
4974                 break;
4975             }
4976 
4977             if(!(c instanceof JComponent)) {
4978                 break;
4979             }
4980         }
4981         if(c instanceof JComponent) {
4982             ((JComponent)c)._paintImmediately(x,y,w,h);
4983         } else {
4984             c.repaint(x,y,w,h);
4985         }
4986     }
4987 
4988     /**
4989      * Paints the specified region now.
4990      *
4991      * @param r a <code>Rectangle</code> containing the region to be painted
4992      */
4993     public void paintImmediately(Rectangle r) {
4994         paintImmediately(r.x,r.y,r.width,r.height);
4995     }
4996 
4997     /**
4998      * Returns whether this component should be guaranteed to be on top.
4999      * For example, it would make no sense for <code>Menu</code>s to pop up
5000      * under another component, so they would always return true.
5001      * Most components will want to return false, hence that is the default.
5002      *
5003      * @return always returns false
5004      */
5005     // package private
5006     boolean alwaysOnTop() {
5007         return false;
5008     }
5009 
5010     void setPaintingChild(Component paintingChild) {
5011         this.paintingChild = paintingChild;
5012     }
5013 
5014     void _paintImmediately(int x, int y, int w, int h) {
5015         Graphics g;
5016         Container c;
5017         Rectangle b;
5018 
5019         int tmpX, tmpY, tmpWidth, tmpHeight;
5020         int offsetX=0,offsetY=0;
5021 
5022         boolean hasBuffer = false;
5023 
5024         JComponent bufferedComponent = null;
5025         JComponent paintingComponent = this;
5026 
5027         RepaintManager repaintManager = RepaintManager.currentManager(this);
5028         // parent Container's up to Window or Applet. First container is
5029         // the direct parent. Note that in testing it was faster to
5030         // alloc a new Vector vs keeping a stack of them around, and gc
5031         // seemed to have a minimal effect on this.
5032         java.util.List<Component> path = new java.util.ArrayList<Component>(7);
5033         int pIndex = -1;
5034         int pCount = 0;
5035 
5036         tmpX = tmpY = tmpWidth = tmpHeight = 0;
5037 
5038         Rectangle paintImmediatelyClip = fetchRectangle();
5039         paintImmediatelyClip.x = x;
5040         paintImmediatelyClip.y = y;
5041         paintImmediatelyClip.width = w;
5042         paintImmediatelyClip.height = h;
5043 
5044 
5045         // System.out.println("1) ************* in _paintImmediately for " + this);
5046 
5047         boolean ontop = alwaysOnTop() && isOpaque();
5048         if (ontop) {
5049             SwingUtilities.computeIntersection(0, 0, getWidth(), getHeight(),
5050                                                paintImmediatelyClip);
5051             if (paintImmediatelyClip.width == 0) {
5052                 recycleRectangle(paintImmediatelyClip);
5053                 return;
5054             }
5055         }
5056         Component child;
5057         for (c = this, child = null;
5058              c != null && !(c instanceof Window) && !(c instanceof Applet);
5059              child = c, c = c.getParent()) {
5060                 JComponent jc = (c instanceof JComponent) ? (JComponent)c :
5061                                 null;
5062                 path.add(c);
5063                 if(!ontop && jc != null && !jc.isOptimizedDrawingEnabled()) {
5064                     boolean resetPC;
5065 
5066                     // Children of c may overlap, three possible cases for the
5067                     // painting region:
5068                     // . Completely obscured by an opaque sibling, in which
5069                     //   case there is no need to paint.
5070                     // . Partially obscured by a sibling: need to start
5071                     //   painting from c.
5072                     // . Otherwise we aren't obscured and thus don't need to
5073                     //   start painting from parent.
5074                     if (c != this) {
5075                         if (jc.isPaintingOrigin()) {
5076                             resetPC = true;
5077                         }
5078                         else {
5079                             Component[] children = c.getComponents();
5080                             int i = 0;
5081                             for (; i<children.length; i++) {
5082                                 if (children[i] == child) break;
5083                             }
5084                             switch (jc.getObscuredState(i,
5085                                             paintImmediatelyClip.x,
5086                                             paintImmediatelyClip.y,
5087                                             paintImmediatelyClip.width,
5088                                             paintImmediatelyClip.height)) {
5089                             case NOT_OBSCURED:
5090                                 resetPC = false;
5091                                 break;
5092                             case COMPLETELY_OBSCURED:
5093                                 recycleRectangle(paintImmediatelyClip);
5094                                 return;
5095                             default:
5096                                 resetPC = true;
5097                                 break;
5098                             }
5099                         }
5100                     }
5101                     else {
5102                         resetPC = false;
5103                     }
5104 
5105                     if (resetPC) {
5106                         // Get rid of any buffer since we draw from here and
5107                         // we might draw something larger
5108                         paintingComponent = jc;
5109                         pIndex = pCount;
5110                         offsetX = offsetY = 0;
5111                         hasBuffer = false;
5112                     }
5113                 }
5114                 pCount++;
5115 
5116                 // look to see if the parent (and therefor this component)
5117                 // is double buffered
5118                 if(repaintManager.isDoubleBufferingEnabled() && jc != null &&
5119                                   jc.isDoubleBuffered()) {
5120                     hasBuffer = true;
5121                     bufferedComponent = jc;
5122                 }
5123 
5124                 // if we aren't on top, include the parent's clip
5125                 if (!ontop) {
5126                     int bx = c.getX();
5127                     int by = c.getY();
5128                     tmpWidth = c.getWidth();
5129                     tmpHeight = c.getHeight();
5130                     SwingUtilities.computeIntersection(tmpX,tmpY,tmpWidth,tmpHeight,paintImmediatelyClip);
5131                     paintImmediatelyClip.x += bx;
5132                     paintImmediatelyClip.y += by;
5133                     offsetX += bx;
5134                     offsetY += by;
5135                 }
5136         }
5137 
5138         // If the clip width or height is negative, don't bother painting
5139         if(c == null || c.getPeer() == null ||
5140                         paintImmediatelyClip.width <= 0 ||
5141                         paintImmediatelyClip.height <= 0) {
5142             recycleRectangle(paintImmediatelyClip);
5143             return;
5144         }
5145 
5146         paintingComponent.setFlag(IS_REPAINTING, true);
5147 
5148         paintImmediatelyClip.x -= offsetX;
5149         paintImmediatelyClip.y -= offsetY;
5150 
5151         // Notify the Components that are going to be painted of the
5152         // child component to paint to.
5153         if(paintingComponent != this) {
5154             Component comp;
5155             int i = pIndex;
5156             for(; i > 0 ; i--) {
5157                 comp = path.get(i);
5158                 if(comp instanceof JComponent) {
5159                     ((JComponent)comp).setPaintingChild(path.get(i-1));
5160                 }
5161             }
5162         }
5163         try {
5164             if ((g = safelyGetGraphics(paintingComponent, c)) != null) {
5165                 try {
5166                     if (hasBuffer) {
5167                         RepaintManager rm = RepaintManager.currentManager(
5168                                 bufferedComponent);
5169                         rm.beginPaint();
5170                         try {
5171                             rm.paint(paintingComponent, bufferedComponent, g,
5172                                     paintImmediatelyClip.x,
5173                                     paintImmediatelyClip.y,
5174                                     paintImmediatelyClip.width,
5175                                     paintImmediatelyClip.height);
5176                         } finally {
5177                             rm.endPaint();
5178                         }
5179                     } else {
5180                         g.setClip(paintImmediatelyClip.x, paintImmediatelyClip.y,
5181                                 paintImmediatelyClip.width, paintImmediatelyClip.height);
5182                         paintingComponent.paint(g);
5183                     }
5184                 } finally {
5185                     g.dispose();
5186                 }
5187             }
5188         }
5189         finally {
5190             // Reset the painting child for the parent components.
5191             if(paintingComponent != this) {
5192                 Component comp;
5193                 int i = pIndex;
5194                 for(; i > 0 ; i--) {
5195                     comp = path.get(i);
5196                     if(comp instanceof JComponent) {
5197                         ((JComponent)comp).setPaintingChild(null);
5198                     }
5199                 }
5200             }
5201             paintingComponent.setFlag(IS_REPAINTING, false);
5202         }
5203         recycleRectangle(paintImmediatelyClip);
5204     }
5205 
5206     /**
5207      * Paints to the specified graphics.  This does not set the clip and it
5208      * does not adjust the Graphics in anyway, callers must do that first.
5209      * This method is package-private for RepaintManager.PaintManager and
5210      * its subclasses to call, it is NOT intended for general use outside
5211      * of that.
5212      */
5213     void paintToOffscreen(Graphics g, int x, int y, int w, int h, int maxX,
5214                           int maxY) {
5215         try {
5216             setFlag(ANCESTOR_USING_BUFFER, true);
5217             if ((y + h) < maxY || (x + w) < maxX) {
5218                 setFlag(IS_PAINTING_TILE, true);
5219             }
5220             if (getFlag(IS_REPAINTING)) {
5221                 // Called from paintImmediately (RepaintManager) to fill
5222                 // repaint request
5223                 paint(g);
5224             } else {
5225                 // Called from paint() (AWT) to repair damage
5226                 if(!rectangleIsObscured(x, y, w, h)) {
5227                     paintComponent(g);
5228                     paintBorder(g);
5229                 }
5230                 paintChildren(g);
5231             }
5232         } finally {
5233             setFlag(ANCESTOR_USING_BUFFER, false);
5234             setFlag(IS_PAINTING_TILE, false);
5235         }
5236     }
5237 
5238     /**
5239      * Returns whether or not the region of the specified component is
5240      * obscured by a sibling.
5241      *
5242      * @return NOT_OBSCURED if non of the siblings above the Component obscure
5243      *         it, COMPLETELY_OBSCURED if one of the siblings completely
5244      *         obscures the Component or PARTIALLY_OBSCURED if the Component is
5245      *         only partially obscured.
5246      */
5247     private int getObscuredState(int compIndex, int x, int y, int width,
5248                                  int height) {
5249         int retValue = NOT_OBSCURED;
5250         Rectangle tmpRect = fetchRectangle();
5251 
5252         for (int i = compIndex - 1 ; i >= 0 ; i--) {
5253             Component sibling = getComponent(i);
5254             if (!sibling.isVisible()) {
5255                 continue;
5256             }
5257             Rectangle siblingRect;
5258             boolean opaque;
5259             if (sibling instanceof JComponent) {
5260                 opaque = sibling.isOpaque();
5261                 if (!opaque) {
5262                     if (retValue == PARTIALLY_OBSCURED) {
5263                         continue;
5264                     }
5265                 }
5266             }
5267             else {
5268                 opaque = true;
5269             }
5270             siblingRect = sibling.getBounds(tmpRect);
5271             if (opaque && x >= siblingRect.x && (x + width) <=
5272                      (siblingRect.x + siblingRect.width) &&
5273                      y >= siblingRect.y && (y + height) <=
5274                      (siblingRect.y + siblingRect.height)) {
5275                 recycleRectangle(tmpRect);
5276                 return COMPLETELY_OBSCURED;
5277             }
5278             else if (retValue == NOT_OBSCURED &&
5279                      !((x + width <= siblingRect.x) ||
5280                        (y + height <= siblingRect.y) ||
5281                        (x >= siblingRect.x + siblingRect.width) ||
5282                        (y >= siblingRect.y + siblingRect.height))) {
5283                 retValue = PARTIALLY_OBSCURED;
5284             }
5285         }
5286         recycleRectangle(tmpRect);
5287         return retValue;
5288     }
5289 
5290     /**
5291      * Returns true, which implies that before checking if a child should
5292      * be painted it is first check that the child is not obscured by another
5293      * sibling. This is only checked if <code>isOptimizedDrawingEnabled</code>
5294      * returns false.
5295      *
5296      * @return always returns true
5297      */
5298     boolean checkIfChildObscuredBySibling() {
5299         return true;
5300     }
5301 
5302 
5303     private void setFlag(int aFlag, boolean aValue) {
5304         if(aValue) {
5305             flags |= (1 << aFlag);
5306         } else {
5307             flags &= ~(1 << aFlag);
5308         }
5309     }
5310     private boolean getFlag(int aFlag) {
5311         int mask = (1 << aFlag);
5312         return ((flags & mask) == mask);
5313     }
5314     // These functions must be static so that they can be called from
5315     // subclasses inside the package, but whose inheritance hierarhcy includes
5316     // classes outside of the package below JComponent (e.g., JTextArea).
5317     static void setWriteObjCounter(JComponent comp, byte count) {
5318         comp.flags = (comp.flags & ~(0xFF << WRITE_OBJ_COUNTER_FIRST)) |
5319                      (count << WRITE_OBJ_COUNTER_FIRST);
5320     }
5321     static byte getWriteObjCounter(JComponent comp) {
5322         return (byte)((comp.flags >> WRITE_OBJ_COUNTER_FIRST) & 0xFF);
5323     }
5324 
5325     /** Buffering **/
5326 
5327     /**
5328      *  Sets whether this component should use a buffer to paint.
5329      *  If set to true, all the drawing from this component will be done
5330      *  in an offscreen painting buffer. The offscreen painting buffer will
5331      *  the be copied onto the screen.
5332      *  If a <code>Component</code> is buffered and one of its ancestor
5333      *  is also buffered, the ancestor buffer will be used.
5334      *
5335      *  @param aFlag if true, set this component to be double buffered
5336      */
5337     public void setDoubleBuffered(boolean aFlag) {
5338         setFlag(IS_DOUBLE_BUFFERED,aFlag);
5339     }
5340 
5341     /**
5342      * Returns whether this component should use a buffer to paint.
5343      *
5344      * @return true if this component is double buffered, otherwise false
5345      */
5346     public boolean isDoubleBuffered() {
5347         return getFlag(IS_DOUBLE_BUFFERED);
5348     }
5349 
5350     /**
5351      * Returns the <code>JRootPane</code> ancestor for this component.
5352      *
5353      * @return the <code>JRootPane</code> that contains this component,
5354      *          or <code>null</code> if no <code>JRootPane</code> is found
5355      */
5356     public JRootPane getRootPane() {
5357         return SwingUtilities.getRootPane(this);
5358     }
5359 
5360 
5361     /** Serialization **/
5362 
5363     /**
5364      * This is called from Component by way of reflection. Do NOT change
5365      * the name unless you change the code in Component as well.
5366      */
5367     void compWriteObjectNotify() {
5368         byte count = JComponent.getWriteObjCounter(this);
5369         JComponent.setWriteObjCounter(this, (byte)(count + 1));
5370         if (count != 0) {
5371             return;
5372         }
5373 
5374         uninstallUIAndProperties();
5375 
5376         /* JTableHeader is in a separate package, which prevents it from
5377          * being able to override this package-private method the way the
5378          * other components can.  We don't want to make this method protected
5379          * because it would introduce public-api for a less-than-desirable
5380          * serialization scheme, so we compromise with this 'instanceof' hack
5381          * for now.
5382          */
5383         if (getToolTipText() != null ||
5384             this instanceof javax.swing.table.JTableHeader) {
5385             ToolTipManager.sharedInstance().unregisterComponent(JComponent.this);
5386         }
5387     }
5388 
5389     /**
5390      * This object is the <code>ObjectInputStream</code> callback
5391      * that's called after a complete graph of objects (including at least
5392      * one <code>JComponent</code>) has been read.
5393      *  It sets the UI property of each Swing component
5394      * that was read to the current default with <code>updateUI</code>.
5395      * <p>
5396      * As each  component is read in we keep track of the current set of
5397      * root components here, in the roots vector.  Note that there's only one
5398      * <code>ReadObjectCallback</code> per <code>ObjectInputStream</code>,
5399      * they're stored in the static <code>readObjectCallbacks</code>
5400      * hashtable.
5401      *
5402      * @see java.io.ObjectInputStream#registerValidation
5403      * @see SwingUtilities#updateComponentTreeUI
5404      */
5405     private class ReadObjectCallback implements ObjectInputValidation
5406     {
5407         private final Vector<JComponent> roots = new Vector<JComponent>(1);
5408         private final ObjectInputStream inputStream;
5409 
5410         ReadObjectCallback(ObjectInputStream s) throws Exception {
5411             inputStream = s;
5412             s.registerValidation(this, 0);
5413         }
5414 
5415         /**
5416          * This is the method that's called after the entire graph
5417          * of objects has been read in.  It initializes
5418          * the UI property of all of the copmonents with
5419          * <code>SwingUtilities.updateComponentTreeUI</code>.
5420          */
5421         public void validateObject() throws InvalidObjectException {
5422             try {
5423                 for (JComponent root : roots) {
5424                     SwingUtilities.updateComponentTreeUI(root);
5425                 }
5426             }
5427             finally {
5428                 readObjectCallbacks.remove(inputStream);
5429             }
5430         }
5431 
5432         /**
5433          * If <code>c</code> isn't a descendant of a component we've already
5434          * seen, then add it to the roots <code>Vector</code>.
5435          *
5436          * @param c the <code>JComponent</code> to add
5437          */
5438         private void registerComponent(JComponent c)
5439         {
5440             /* If the Component c is a descendant of one of the
5441              * existing roots (or it IS an existing root), we're done.
5442              */
5443             for (JComponent root : roots) {
5444                 for(Component p = c; p != null; p = p.getParent()) {
5445                     if (p == root) {
5446                         return;
5447                     }
5448                 }
5449             }
5450 
5451             /* Otherwise: if Component c is an ancestor of any of the
5452              * existing roots then remove them and add c (the "new root")
5453              * to the roots vector.
5454              */
5455             for(int i = 0; i < roots.size(); i++) {
5456                 JComponent root = roots.elementAt(i);
5457                 for(Component p = root.getParent(); p != null; p = p.getParent()) {
5458                     if (p == c) {
5459                         roots.removeElementAt(i--); // !!
5460                         break;
5461                     }
5462                 }
5463             }
5464 
5465             roots.addElement(c);
5466         }
5467     }
5468 
5469 
5470     /**
5471      * We use the <code>ObjectInputStream</code> "registerValidation"
5472      * callback to update the UI for the entire tree of components
5473      * after they've all been read in.
5474      *
5475      * @param s  the <code>ObjectInputStream</code> from which to read
5476      */
5477     private void readObject(ObjectInputStream s)
5478         throws IOException, ClassNotFoundException
5479     {
5480         s.defaultReadObject();
5481 
5482         /* If there's no ReadObjectCallback for this stream yet, that is, if
5483          * this is the first call to JComponent.readObject() for this
5484          * graph of objects, then create a callback and stash it
5485          * in the readObjectCallbacks table.  Note that the ReadObjectCallback
5486          * constructor takes care of calling s.registerValidation().
5487          */
5488         ReadObjectCallback cb = readObjectCallbacks.get(s);
5489         if (cb == null) {
5490             try {
5491                 readObjectCallbacks.put(s, cb = new ReadObjectCallback(s));
5492             }
5493             catch (Exception e) {
5494                 throw new IOException(e.toString());
5495             }
5496         }
5497         cb.registerComponent(this);
5498 
5499         // Read back the client properties.
5500         int cpCount = s.readInt();
5501         if (cpCount > 0) {
5502             clientProperties = new ArrayTable();
5503             for (int counter = 0; counter < cpCount; counter++) {
5504                 clientProperties.put(s.readObject(),
5505                                      s.readObject());
5506             }
5507         }
5508         if (getToolTipText() != null) {
5509             ToolTipManager.sharedInstance().registerComponent(this);
5510         }
5511         setWriteObjCounter(this, (byte)0);
5512     }
5513 
5514 
5515     /**
5516      * Before writing a <code>JComponent</code> to an
5517      * <code>ObjectOutputStream</code> we temporarily uninstall its UI.
5518      * This is tricky to do because we want to uninstall
5519      * the UI before any of the <code>JComponent</code>'s children
5520      * (or its <code>LayoutManager</code> etc.) are written,
5521      * and we don't want to restore the UI until the most derived
5522      * <code>JComponent</code> subclass has been been stored.
5523      *
5524      * @param s the <code>ObjectOutputStream</code> in which to write
5525      */
5526     private void writeObject(ObjectOutputStream s) throws IOException {
5527         s.defaultWriteObject();
5528         if (getUIClassID().equals(uiClassID)) {
5529             byte count = JComponent.getWriteObjCounter(this);
5530             JComponent.setWriteObjCounter(this, --count);
5531             if (count == 0 && ui != null) {
5532                 ui.installUI(this);
5533             }
5534         }
5535         ArrayTable.writeArrayTable(s, clientProperties);
5536     }
5537 
5538 
5539     /**
5540      * Returns a string representation of this <code>JComponent</code>.
5541      * This method
5542      * is intended to be used only for debugging purposes, and the
5543      * content and format of the returned string may vary between
5544      * implementations. The returned string may be empty but may not
5545      * be <code>null</code>.
5546      *
5547      * @return  a string representation of this <code>JComponent</code>
5548      */
5549     protected String paramString() {
5550         String preferredSizeString = (isPreferredSizeSet() ?
5551                                       getPreferredSize().toString() : "");
5552         String minimumSizeString = (isMinimumSizeSet() ?
5553                                     getMinimumSize().toString() : "");
5554         String maximumSizeString = (isMaximumSizeSet() ?
5555                                     getMaximumSize().toString() : "");
5556         String borderString = (border == null ? ""
5557                                : (border == this ? "this" : border.toString()));
5558 
5559         return super.paramString() +
5560         ",alignmentX=" + alignmentX +
5561         ",alignmentY=" + alignmentY +
5562         ",border=" + borderString +
5563         ",flags=" + flags +             // should beef this up a bit
5564         ",maximumSize=" + maximumSizeString +
5565         ",minimumSize=" + minimumSizeString +
5566         ",preferredSize=" + preferredSizeString;
5567     }
5568 
5569     /**
5570      * {@inheritDoc}
5571      */
5572     @Override
5573     @Deprecated
5574     public void hide() {
5575         boolean showing = isShowing();
5576         super.hide();
5577         if (showing) {
5578             Container parent = getParent();
5579             if (parent != null) {
5580                 Rectangle r = getBounds();
5581                 parent.repaint(r.x, r.y, r.width, r.height);
5582             }
5583             revalidate();
5584         }
5585     }
5586 
5587 }