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