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