1 /*
   2  * Copyright 1995-2009 Sun Microsystems, Inc.  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.  Sun designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  22  * CA 95054 USA or visit www.sun.com if you need additional information or
  23  * have any questions.
  24  */
  25 package java.awt;
  26 
  27 import java.io.PrintStream;
  28 import java.io.PrintWriter;
  29 import java.util.Vector;
  30 import java.util.Locale;
  31 import java.util.EventListener;
  32 import java.util.Iterator;
  33 import java.util.HashSet;
  34 import java.util.Map;
  35 import java.util.Set;
  36 import java.util.Collections;
  37 import java.awt.peer.ComponentPeer;
  38 import java.awt.peer.ContainerPeer;
  39 import java.awt.peer.LightweightPeer;
  40 import java.awt.image.BufferStrategy;
  41 import java.awt.image.ImageObserver;
  42 import java.awt.image.ImageProducer;
  43 import java.awt.image.ColorModel;
  44 import java.awt.image.VolatileImage;
  45 import java.awt.event.*;
  46 import java.io.Serializable;
  47 import java.io.ObjectOutputStream;
  48 import java.io.ObjectInputStream;
  49 import java.io.IOException;
  50 import java.beans.PropertyChangeListener;
  51 import java.beans.PropertyChangeSupport;
  52 import java.beans.Transient;
  53 import java.awt.event.InputMethodListener;
  54 import java.awt.event.InputMethodEvent;
  55 import java.awt.im.InputContext;
  56 import java.awt.im.InputMethodRequests;
  57 import java.awt.dnd.DropTarget;
  58 import java.lang.reflect.InvocationTargetException;
  59 import java.lang.reflect.Method;
  60 import java.security.AccessController;
  61 import java.security.PrivilegedAction;
  62 import javax.accessibility.*;
  63 import java.util.logging.*;
  64 import java.applet.Applet;
  65 
  66 import sun.security.action.GetPropertyAction;
  67 import sun.awt.AppContext;
  68 import sun.awt.AWTAccessor;
  69 import sun.awt.ConstrainableGraphics;
  70 import sun.awt.SubRegionShowable;
  71 import sun.awt.SunToolkit;
  72 import sun.awt.WindowClosingListener;
  73 import sun.awt.CausedFocusEvent;
  74 import sun.awt.EmbeddedFrame;
  75 import sun.awt.dnd.SunDropTargetEvent;
  76 import sun.awt.im.CompositionArea;
  77 import sun.java2d.SunGraphics2D;
  78 import sun.java2d.pipe.Region;
  79 import sun.awt.image.VSyncedBSManager;
  80 import sun.java2d.pipe.hw.ExtendedBufferCapabilities;
  81 import static sun.java2d.pipe.hw.ExtendedBufferCapabilities.VSyncType.*;
  82 import sun.awt.RequestFocusController;
  83 import sun.java2d.SunGraphicsEnvironment;
  84 
  85 /**
  86  * A <em>component</em> is an object having a graphical representation
  87  * that can be displayed on the screen and that can interact with the
  88  * user. Examples of components are the buttons, checkboxes, and scrollbars
  89  * of a typical graphical user interface. <p>
  90  * The <code>Component</code> class is the abstract superclass of
  91  * the nonmenu-related Abstract Window Toolkit components. Class
  92  * <code>Component</code> can also be extended directly to create a
  93  * lightweight component. A lightweight component is a component that is
  94  * not associated with a native window. On the contrary, a heavyweight
  95  * component is associated with a native window. The {@link #isLightweight()}
  96  * method may be used to distinguish between the two kinds of the components.
  97  * <p>
  98  * Lightweight and heavyweight components may be mixed in a single component
  99  * hierarchy. However, for correct operating of such a mixed hierarchy of
 100  * components, the whole hierarchy must be valid. When the hierarchy gets
 101  * invalidated, like after changing the bounds of components, or
 102  * adding/removing components to/from containers, the whole hierarchy must be
 103  * validated afterwards by means of the {@link Container#validate()} method
 104  * invoked on the top-most invalid container of the hierarchy.
 105  * <p>
 106  * <h3>Serialization</h3>
 107  * It is important to note that only AWT listeners which conform
 108  * to the <code>Serializable</code> protocol will be saved when
 109  * the object is stored.  If an AWT object has listeners that
 110  * aren't marked serializable, they will be dropped at
 111  * <code>writeObject</code> time.  Developers will need, as always,
 112  * to consider the implications of making an object serializable.
 113  * One situation to watch out for is this:
 114  * <pre>
 115  *    import java.awt.*;
 116  *    import java.awt.event.*;
 117  *    import java.io.Serializable;
 118  *
 119  *    class MyApp implements ActionListener, Serializable
 120  *    {
 121  *        BigObjectThatShouldNotBeSerializedWithAButton bigOne;
 122  *        Button aButton = new Button();
 123  *
 124  *        MyApp()
 125  *        {
 126  *            // Oops, now aButton has a listener with a reference
 127  *            // to bigOne!
 128  *            aButton.addActionListener(this);
 129  *        }
 130  *
 131  *        public void actionPerformed(ActionEvent e)
 132  *        {
 133  *            System.out.println("Hello There");
 134  *        }
 135  *    }
 136  * </pre>
 137  * In this example, serializing <code>aButton</code> by itself
 138  * will cause <code>MyApp</code> and everything it refers to
 139  * to be serialized as well.  The problem is that the listener
 140  * is serializable by coincidence, not by design.  To separate
 141  * the decisions about <code>MyApp</code> and the
 142  * <code>ActionListener</code> being serializable one can use a
 143  * nested class, as in the following example:
 144  * <pre>
 145  *    import java.awt.*;
 146  *    import java.awt.event.*;
 147  *    import java.io.Serializable;
 148  *
 149  *    class MyApp java.io.Serializable
 150  *    {
 151  *         BigObjectThatShouldNotBeSerializedWithAButton bigOne;
 152  *         Button aButton = new Button();
 153  *
 154  *         static class MyActionListener implements ActionListener
 155  *         {
 156  *             public void actionPerformed(ActionEvent e)
 157  *             {
 158  *                 System.out.println("Hello There");
 159  *             }
 160  *         }
 161  *
 162  *         MyApp()
 163  *         {
 164  *             aButton.addActionListener(new MyActionListener());
 165  *         }
 166  *    }
 167  * </pre>
 168  * <p>
 169  * <b>Note</b>: For more information on the paint mechanisms utilitized
 170  * by AWT and Swing, including information on how to write the most
 171  * efficient painting code, see
 172  * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>.
 173  * <p>
 174  * For details on the focus subsystem, see
 175  * <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
 176  * How to Use the Focus Subsystem</a>,
 177  * a section in <em>The Java Tutorial</em>, and the
 178  * <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
 179  * for more information.
 180  *
 181  * @author      Arthur van Hoff
 182  * @author      Sami Shaio
 183  */
 184 public abstract class Component implements ImageObserver, MenuContainer,
 185                                            Serializable
 186 {
 187 
 188     private static final Logger log = Logger.getLogger("java.awt.Component");
 189     private static final Logger eventLog = Logger.getLogger("java.awt.event.Component");
 190     private static final Logger focusLog = Logger.getLogger("java.awt.focus.Component");
 191     private static final Logger mixingLog = Logger.getLogger("java.awt.mixing.Component");
 192 
 193     /**
 194      * The peer of the component. The peer implements the component's
 195      * behavior. The peer is set when the <code>Component</code> is
 196      * added to a container that also is a peer.
 197      * @see #addNotify
 198      * @see #removeNotify
 199      */
 200     transient ComponentPeer peer;
 201 
 202     /**
 203      * The parent of the object. It may be <code>null</code>
 204      * for top-level components.
 205      * @see #getParent
 206      */
 207     transient Container parent;
 208 
 209     /**
 210      * The <code>AppContext</code> of the component. Applets/Plugin may
 211      * change the AppContext.
 212      */
 213     transient AppContext appContext;
 214 
 215     /**
 216      * The x position of the component in the parent's coordinate system.
 217      *
 218      * @serial
 219      * @see #getLocation
 220      */
 221     int x;
 222 
 223     /**
 224      * The y position of the component in the parent's coordinate system.
 225      *
 226      * @serial
 227      * @see #getLocation
 228      */
 229     int y;
 230 
 231     /**
 232      * The width of the component.
 233      *
 234      * @serial
 235      * @see #getSize
 236      */
 237     int width;
 238 
 239     /**
 240      * The height of the component.
 241      *
 242      * @serial
 243      * @see #getSize
 244      */
 245     int height;
 246 
 247     /**
 248      * The foreground color for this component.
 249      * <code>foreground</code> can be <code>null</code>.
 250      *
 251      * @serial
 252      * @see #getForeground
 253      * @see #setForeground
 254      */
 255     Color       foreground;
 256 
 257     /**
 258      * The background color for this component.
 259      * <code>background</code> can be <code>null</code>.
 260      *
 261      * @serial
 262      * @see #getBackground
 263      * @see #setBackground
 264      */
 265     Color       background;
 266 
 267     /**
 268      * The font used by this component.
 269      * The <code>font</code> can be <code>null</code>.
 270      *
 271      * @serial
 272      * @see #getFont
 273      * @see #setFont
 274      */
 275     Font        font;
 276 
 277     /**
 278      * The font which the peer is currently using.
 279      * (<code>null</code> if no peer exists.)
 280      */
 281     Font        peerFont;
 282 
 283     /**
 284      * The cursor displayed when pointer is over this component.
 285      * This value can be <code>null</code>.
 286      *
 287      * @serial
 288      * @see #getCursor
 289      * @see #setCursor
 290      */
 291     Cursor      cursor;
 292 
 293     /**
 294      * The locale for the component.
 295      *
 296      * @serial
 297      * @see #getLocale
 298      * @see #setLocale
 299      */
 300     Locale      locale;
 301 
 302     /**
 303      * A reference to a <code>GraphicsConfiguration</code> object
 304      * used to describe the characteristics of a graphics
 305      * destination.
 306      * This value can be <code>null</code>.
 307      *
 308      * @since 1.3
 309      * @serial
 310      * @see GraphicsConfiguration
 311      * @see #getGraphicsConfiguration
 312      */
 313     private transient GraphicsConfiguration graphicsConfig = null;
 314 
 315     /**
 316      * A reference to a <code>BufferStrategy</code> object
 317      * used to manipulate the buffers on this component.
 318      *
 319      * @since 1.4
 320      * @see java.awt.image.BufferStrategy
 321      * @see #getBufferStrategy()
 322      */
 323     transient BufferStrategy bufferStrategy = null;
 324 
 325     /**
 326      * True when the object should ignore all repaint events.
 327      *
 328      * @since 1.4
 329      * @serial
 330      * @see #setIgnoreRepaint
 331      * @see #getIgnoreRepaint
 332      */
 333     boolean ignoreRepaint = false;
 334 
 335     /**
 336      * True when the object is visible. An object that is not
 337      * visible is not drawn on the screen.
 338      *
 339      * @serial
 340      * @see #isVisible
 341      * @see #setVisible
 342      */
 343     boolean visible = true;
 344 
 345     /**
 346      * True when the object is enabled. An object that is not
 347      * enabled does not interact with the user.
 348      *
 349      * @serial
 350      * @see #isEnabled
 351      * @see #setEnabled
 352      */
 353     boolean enabled = true;
 354 
 355     /**
 356      * True when the object is valid. An invalid object needs to
 357      * be layed out. This flag is set to false when the object
 358      * size is changed.
 359      *
 360      * @serial
 361      * @see #isValid
 362      * @see #validate
 363      * @see #invalidate
 364      */
 365     private volatile boolean valid = false;
 366 
 367     /**
 368      * The <code>DropTarget</code> associated with this component.
 369      *
 370      * @since 1.2
 371      * @serial
 372      * @see #setDropTarget
 373      * @see #getDropTarget
 374      */
 375     DropTarget dropTarget;
 376 
 377     /**
 378      * @serial
 379      * @see #add
 380      */
 381     Vector popups;
 382 
 383     /**
 384      * A component's name.
 385      * This field can be <code>null</code>.
 386      *
 387      * @serial
 388      * @see #getName
 389      * @see #setName(String)
 390      */
 391     private String name;
 392 
 393     /**
 394      * A bool to determine whether the name has
 395      * been set explicitly. <code>nameExplicitlySet</code> will
 396      * be false if the name has not been set and
 397      * true if it has.
 398      *
 399      * @serial
 400      * @see #getName
 401      * @see #setName(String)
 402      */
 403     private boolean nameExplicitlySet = false;
 404 
 405     /**
 406      * Indicates whether this Component can be focused.
 407      *
 408      * @serial
 409      * @see #setFocusable
 410      * @see #isFocusable
 411      * @since 1.4
 412      */
 413     private boolean focusable = true;
 414 
 415     private static final int FOCUS_TRAVERSABLE_UNKNOWN = 0;
 416     private static final int FOCUS_TRAVERSABLE_DEFAULT = 1;
 417     private static final int FOCUS_TRAVERSABLE_SET = 2;
 418 
 419     /**
 420      * Tracks whether this Component is relying on default focus travesability.
 421      *
 422      * @serial
 423      * @since 1.4
 424      */
 425     private int isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN;
 426 
 427     /**
 428      * The focus traversal keys. These keys will generate focus traversal
 429      * behavior for Components for which focus traversal keys are enabled. If a
 430      * value of null is specified for a traversal key, this Component inherits
 431      * that traversal key from its parent. If all ancestors of this Component
 432      * have null specified for that traversal key, then the current
 433      * KeyboardFocusManager's default traversal key is used.
 434      *
 435      * @serial
 436      * @see #setFocusTraversalKeys
 437      * @see #getFocusTraversalKeys
 438      * @since 1.4
 439      */
 440     Set[] focusTraversalKeys;
 441 
 442     private static final String[] focusTraversalKeyPropertyNames = {
 443         "forwardFocusTraversalKeys",
 444         "backwardFocusTraversalKeys",
 445         "upCycleFocusTraversalKeys",
 446         "downCycleFocusTraversalKeys"
 447     };
 448 
 449     /**
 450      * Indicates whether focus traversal keys are enabled for this Component.
 451      * Components for which focus traversal keys are disabled receive key
 452      * events for focus traversal keys. Components for which focus traversal
 453      * keys are enabled do not see these events; instead, the events are
 454      * automatically converted to traversal operations.
 455      *
 456      * @serial
 457      * @see #setFocusTraversalKeysEnabled
 458      * @see #getFocusTraversalKeysEnabled
 459      * @since 1.4
 460      */
 461     private boolean focusTraversalKeysEnabled = true;
 462 
 463     /**
 464      * The locking object for AWT component-tree and layout operations.
 465      *
 466      * @see #getTreeLock
 467      */
 468     static final Object LOCK = new AWTTreeLock();
 469     static class AWTTreeLock {}
 470 
 471     /**
 472      * Minimum size.
 473      * (This field perhaps should have been transient).
 474      *
 475      * @serial
 476      */
 477     Dimension minSize;
 478 
 479     /**
 480      * Whether or not setMinimumSize has been invoked with a non-null value.
 481      */
 482     boolean minSizeSet;
 483 
 484     /**
 485      * Preferred size.
 486      * (This field perhaps should have been transient).
 487      *
 488      * @serial
 489      */
 490     Dimension prefSize;
 491 
 492     /**
 493      * Whether or not setPreferredSize has been invoked with a non-null value.
 494      */
 495     boolean prefSizeSet;
 496 
 497     /**
 498      * Maximum size
 499      *
 500      * @serial
 501      */
 502     Dimension maxSize;
 503 
 504     /**
 505      * Whether or not setMaximumSize has been invoked with a non-null value.
 506      */
 507     boolean maxSizeSet;
 508 
 509     /**
 510      * The orientation for this component.
 511      * @see #getComponentOrientation
 512      * @see #setComponentOrientation
 513      */
 514     transient ComponentOrientation componentOrientation
 515     = ComponentOrientation.UNKNOWN;
 516 
 517     /**
 518      * <code>newEventsOnly</code> will be true if the event is
 519      * one of the event types enabled for the component.
 520      * It will then allow for normal processing to
 521      * continue.  If it is false the event is passed
 522      * to the component's parent and up the ancestor
 523      * tree until the event has been consumed.
 524      *
 525      * @serial
 526      * @see #dispatchEvent
 527      */
 528     boolean newEventsOnly = false;
 529     transient ComponentListener componentListener;
 530     transient FocusListener focusListener;
 531     transient HierarchyListener hierarchyListener;
 532     transient HierarchyBoundsListener hierarchyBoundsListener;
 533     transient KeyListener keyListener;
 534     transient MouseListener mouseListener;
 535     transient MouseMotionListener mouseMotionListener;
 536     transient MouseWheelListener mouseWheelListener;
 537     transient InputMethodListener inputMethodListener;
 538 
 539     transient RuntimeException windowClosingException = null;
 540 
 541     /** Internal, constants for serialization */
 542     final static String actionListenerK = "actionL";
 543     final static String adjustmentListenerK = "adjustmentL";
 544     final static String componentListenerK = "componentL";
 545     final static String containerListenerK = "containerL";
 546     final static String focusListenerK = "focusL";
 547     final static String itemListenerK = "itemL";
 548     final static String keyListenerK = "keyL";
 549     final static String mouseListenerK = "mouseL";
 550     final static String mouseMotionListenerK = "mouseMotionL";
 551     final static String mouseWheelListenerK = "mouseWheelL";
 552     final static String textListenerK = "textL";
 553     final static String ownedWindowK = "ownedL";
 554     final static String windowListenerK = "windowL";
 555     final static String inputMethodListenerK = "inputMethodL";
 556     final static String hierarchyListenerK = "hierarchyL";
 557     final static String hierarchyBoundsListenerK = "hierarchyBoundsL";
 558     final static String windowStateListenerK = "windowStateL";
 559     final static String windowFocusListenerK = "windowFocusL";
 560 
 561     /**
 562      * The <code>eventMask</code> is ONLY set by subclasses via
 563      * <code>enableEvents</code>.
 564      * The mask should NOT be set when listeners are registered
 565      * so that we can distinguish the difference between when
 566      * listeners request events and subclasses request them.
 567      * One bit is used to indicate whether input methods are
 568      * enabled; this bit is set by <code>enableInputMethods</code> and is
 569      * on by default.
 570      *
 571      * @serial
 572      * @see #enableInputMethods
 573      * @see AWTEvent
 574      */
 575     long eventMask = AWTEvent.INPUT_METHODS_ENABLED_MASK;
 576 
 577     /**
 578      * Static properties for incremental drawing.
 579      * @see #imageUpdate
 580      */
 581     static boolean isInc;
 582     static int incRate;
 583     static {
 584         /* ensure that the necessary native libraries are loaded */
 585         Toolkit.loadLibraries();
 586         /* initialize JNI field and method ids */
 587         if (!GraphicsEnvironment.isHeadless()) {
 588             initIDs();
 589         }
 590 
 591         String s = (String) java.security.AccessController.doPrivileged(
 592                                                                         new GetPropertyAction("awt.image.incrementaldraw"));
 593         isInc = (s == null || s.equals("true"));
 594 
 595         s = (String) java.security.AccessController.doPrivileged(
 596                                                                  new GetPropertyAction("awt.image.redrawrate"));
 597         incRate = (s != null) ? Integer.parseInt(s) : 100;
 598     }
 599 
 600     /**
 601      * Ease-of-use constant for <code>getAlignmentY()</code>.
 602      * Specifies an alignment to the top of the component.
 603      * @see     #getAlignmentY
 604      */
 605     public static final float TOP_ALIGNMENT = 0.0f;
 606 
 607     /**
 608      * Ease-of-use constant for <code>getAlignmentY</code> and
 609      * <code>getAlignmentX</code>. Specifies an alignment to
 610      * the center of the component
 611      * @see     #getAlignmentX
 612      * @see     #getAlignmentY
 613      */
 614     public static final float CENTER_ALIGNMENT = 0.5f;
 615 
 616     /**
 617      * Ease-of-use constant for <code>getAlignmentY</code>.
 618      * Specifies an alignment to the bottom of the component.
 619      * @see     #getAlignmentY
 620      */
 621     public static final float BOTTOM_ALIGNMENT = 1.0f;
 622 
 623     /**
 624      * Ease-of-use constant for <code>getAlignmentX</code>.
 625      * Specifies an alignment to the left side of the component.
 626      * @see     #getAlignmentX
 627      */
 628     public static final float LEFT_ALIGNMENT = 0.0f;
 629 
 630     /**
 631      * Ease-of-use constant for <code>getAlignmentX</code>.
 632      * Specifies an alignment to the right side of the component.
 633      * @see     #getAlignmentX
 634      */
 635     public static final float RIGHT_ALIGNMENT = 1.0f;
 636 
 637     /*
 638      * JDK 1.1 serialVersionUID
 639      */
 640     private static final long serialVersionUID = -7644114512714619750L;
 641 
 642     /**
 643      * If any <code>PropertyChangeListeners</code> have been registered,
 644      * the <code>changeSupport</code> field describes them.
 645      *
 646      * @serial
 647      * @since 1.2
 648      * @see #addPropertyChangeListener
 649      * @see #removePropertyChangeListener
 650      * @see #firePropertyChange
 651      */
 652     private PropertyChangeSupport changeSupport;
 653 
 654     /*
 655      * In some cases using "this" as an object to synchronize by
 656      * can lead to a deadlock if client code also uses synchronization
 657      * by a component object. For every such situation revealed we should
 658      * consider possibility of replacing "this" with the package private
 659      * objectLock object introduced below. So far there're 2 issues known:
 660      * - CR 6708322 (the getName/setName methods);
 661      * - CR 6608764 (the PropertyChangeListener machinery).
 662      *
 663      * Note: this field is considered final, though readObject() prohibits
 664      * initializing final fields.
 665      */
 666     private transient Object objectLock = new Object();
 667     Object getObjectLock() {
 668         return objectLock;
 669     }
 670 
 671     boolean isPacked = false;
 672 
 673     /**
 674      * Pseudoparameter for direct Geometry API (setLocation, setBounds setSize
 675      * to signal setBounds what's changing. Should be used under TreeLock.
 676      * This is only needed due to the inability to change the cross-calling
 677      * order of public and deprecated methods.
 678      */
 679     private int boundsOp = ComponentPeer.DEFAULT_OPERATION;
 680 
 681     /**
 682      * Enumeration of the common ways the baseline of a component can
 683      * change as the size changes.  The baseline resize behavior is
 684      * primarily for layout managers that need to know how the
 685      * position of the baseline changes as the component size changes.
 686      * In general the baseline resize behavior will be valid for sizes
 687      * greater than or equal to the minimum size (the actual minimum
 688      * size; not a developer specified minimum size).  For sizes
 689      * smaller than the minimum size the baseline may change in a way
 690      * other than the baseline resize behavior indicates.  Similarly,
 691      * as the size approaches <code>Integer.MAX_VALUE</code> and/or
 692      * <code>Short.MAX_VALUE</code> the baseline may change in a way
 693      * other than the baseline resize behavior indicates.
 694      *
 695      * @see #getBaselineResizeBehavior
 696      * @see #getBaseline(int,int)
 697      * @since 1.6
 698      */
 699     public enum BaselineResizeBehavior {
 700         /**
 701          * Indicates the baseline remains fixed relative to the
 702          * y-origin.  That is, <code>getBaseline</code> returns
 703          * the same value regardless of the height or width.  For example, a
 704          * <code>JLabel</code> containing non-empty text with a
 705          * vertical alignment of <code>TOP</code> should have a
 706          * baseline type of <code>CONSTANT_ASCENT</code>.
 707          */
 708         CONSTANT_ASCENT,
 709 
 710         /**
 711          * Indicates the baseline remains fixed relative to the height
 712          * and does not change as the width is varied.  That is, for
 713          * any height H the difference between H and
 714          * <code>getBaseline(w, H)</code> is the same.  For example, a
 715          * <code>JLabel</code> containing non-empty text with a
 716          * vertical alignment of <code>BOTTOM</code> should have a
 717          * baseline type of <code>CONSTANT_DESCENT</code>.
 718          */
 719         CONSTANT_DESCENT,
 720 
 721         /**
 722          * Indicates the baseline remains a fixed distance from
 723          * the center of the component.  That is, for any height H the
 724          * difference between <code>getBaseline(w, H)</code> and
 725          * <code>H / 2</code> is the same (plus or minus one depending upon
 726          * rounding error).
 727          * <p>
 728          * Because of possible rounding errors it is recommended
 729          * you ask for the baseline with two consecutive heights and use
 730          * the return value to determine if you need to pad calculations
 731          * by 1.  The following shows how to calculate the baseline for
 732          * any height:
 733          * <pre>
 734          *   Dimension preferredSize = component.getPreferredSize();
 735          *   int baseline = getBaseline(preferredSize.width,
 736          *                              preferredSize.height);
 737          *   int nextBaseline = getBaseline(preferredSize.width,
 738          *                                  preferredSize.height + 1);
 739          *   // Amount to add to height when calculating where baseline
 740          *   // lands for a particular height:
 741          *   int padding = 0;
 742          *   // Where the baseline is relative to the mid point
 743          *   int baselineOffset = baseline - height / 2;
 744          *   if (preferredSize.height % 2 == 0 &amp;&amp;
 745          *       baseline != nextBaseline) {
 746          *       padding = 1;
 747          *   }
 748          *   else if (preferredSize.height % 2 == 1 &amp;&amp;
 749          *            baseline == nextBaseline) {
 750          *       baselineOffset--;
 751          *       padding = 1;
 752          *   }
 753          *   // The following calculates where the baseline lands for
 754          *   // the height z:
 755          *   int calculatedBaseline = (z + padding) / 2 + baselineOffset;
 756          * </pre>
 757          */
 758         CENTER_OFFSET,
 759 
 760         /**
 761          * Indicates the baseline resize behavior can not be expressed using
 762          * any of the other constants.  This may also indicate the baseline
 763          * varies with the width of the component.  This is also returned
 764          * by components that do not have a baseline.
 765          */
 766         OTHER
 767     }
 768 
 769     /*
 770      * The shape set with the applyCompoundShape() method. It uncludes the result
 771      * of the HW/LW mixing related shape computation. It may also include
 772      * the user-specified shape of the component.
 773      * The 'null' value means the component has normal shape (or has no shape at all)
 774      * and applyCompoundShape() will skip the following shape identical to normal.
 775      */
 776     private transient Region compoundShape = null;
 777 
 778     /*
 779      * Represents the shape of this lightweight component to be cut out from
 780      * heavyweight components should they intersect. Possible values:
 781      *    1. null - consider the shape rectangular
 782      *    2. EMPTY_REGION - nothing gets cut out (children still get cut out)
 783      *    3. non-empty - this shape gets cut out.
 784      */
 785     private transient Region mixingCutoutRegion = null;
 786 
 787     /*
 788      * Indicates whether addNotify() is complete
 789      * (i.e. the peer is created).
 790      */
 791     private transient boolean isAddNotifyComplete = false;
 792 
 793     /**
 794      * Should only be used in subclass getBounds to check that part of bounds
 795      * is actualy changing
 796      */
 797     int getBoundsOp() {
 798         assert Thread.holdsLock(getTreeLock());
 799         return boundsOp;
 800     }
 801 
 802     void setBoundsOp(int op) {
 803         assert Thread.holdsLock(getTreeLock());
 804         if (op == ComponentPeer.RESET_OPERATION) {
 805             boundsOp = ComponentPeer.DEFAULT_OPERATION;
 806         } else
 807             if (boundsOp == ComponentPeer.DEFAULT_OPERATION) {
 808                 boundsOp = op;
 809             }
 810     }
 811 
 812     // Whether this Component has had the background erase flag
 813     // specified via SunToolkit.disableBackgroundErase(). This is
 814     // needed in order to make this function work on X11 platforms,
 815     // where currently there is no chance to interpose on the creation
 816     // of the peer and therefore the call to XSetBackground.
 817     transient boolean backgroundEraseDisabled;
 818 
 819     static {
 820         AWTAccessor.setComponentAccessor(new AWTAccessor.ComponentAccessor() {
 821             public void setBackgroundEraseDisabled(Component comp, boolean disabled) {
 822                 comp.backgroundEraseDisabled = disabled;
 823             }
 824             public boolean getBackgroundEraseDisabled(Component comp) {
 825                 return comp.backgroundEraseDisabled;
 826             }
 827             public Rectangle getBounds(Component comp) {
 828                 return new Rectangle(comp.x, comp.y, comp.width, comp.height);
 829             }
 830             public void setMixingCutoutShape(Component comp, Shape shape) {
 831                 Region region = shape == null ?  null :
 832                     Region.getInstance(shape, null);
 833 
 834                 synchronized (comp.getTreeLock()) {
 835                     boolean needShowing = false;
 836                     boolean needHiding = false;
 837 
 838                     if (!comp.isNonOpaqueForMixing()) {
 839                         needHiding = true;
 840                     }
 841 
 842                     comp.mixingCutoutRegion = region;
 843 
 844                     if (!comp.isNonOpaqueForMixing()) {
 845                         needShowing = true;
 846                     }
 847 
 848                     if (comp.isMixingNeeded()) {
 849                         if (needHiding) {
 850                             comp.mixOnHiding(comp.isLightweight());
 851                         }
 852                         if (needShowing) {
 853                             comp.mixOnShowing();
 854                         }
 855                     }
 856                 }
 857             }
 858 
 859             public void setGraphicsConfiguration(Component comp,
 860                     GraphicsConfiguration gc)
 861             {
 862                 comp.setGraphicsConfiguration(gc);
 863             }
 864             public boolean requestFocus(Component comp, CausedFocusEvent.Cause cause) {
 865                 return comp.requestFocus(cause);
 866             }
 867             public boolean canBeFocusOwner(Component comp) {
 868                 return comp.canBeFocusOwner();
 869             }
 870 
 871             public boolean isVisible_NoClientCode(Component comp) {
 872                 return comp.isVisible_NoClientCode();
 873             }
 874             public void setRequestFocusController
 875                 (RequestFocusController requestController)
 876             {
 877                  Component.setRequestFocusController(requestController);
 878             }
 879             public AppContext getAppContext(Component comp) {
 880                  return comp.appContext;
 881             }
 882             public void setAppContext(Component comp, AppContext appContext) {
 883                  comp.appContext = appContext;
 884             }
 885         });
 886     }
 887 
 888     /**
 889      * Constructs a new component. Class <code>Component</code> can be
 890      * extended directly to create a lightweight component that does not
 891      * utilize an opaque native window. A lightweight component must be
 892      * hosted by a native container somewhere higher up in the component
 893      * tree (for example, by a <code>Frame</code> object).
 894      */
 895     protected Component() {
 896         appContext = AppContext.getAppContext();
 897     }
 898 
 899     void initializeFocusTraversalKeys() {
 900         focusTraversalKeys = new Set[3];
 901     }
 902 
 903     /**
 904      * Constructs a name for this component.  Called by <code>getName</code>
 905      * when the name is <code>null</code>.
 906      */
 907     String constructComponentName() {
 908         return null; // For strict compliance with prior platform versions, a Component
 909                      // that doesn't set its name should return null from
 910                      // getName()
 911     }
 912 
 913     /**
 914      * Gets the name of the component.
 915      * @return this component's name
 916      * @see    #setName
 917      * @since JDK1.1
 918      */
 919     public String getName() {
 920         if (name == null && !nameExplicitlySet) {
 921             synchronized(getObjectLock()) {
 922                 if (name == null && !nameExplicitlySet)
 923                     name = constructComponentName();
 924             }
 925         }
 926         return name;
 927     }
 928 
 929     /**
 930      * Sets the name of the component to the specified string.
 931      * @param name  the string that is to be this
 932      *           component's name
 933      * @see #getName
 934      * @since JDK1.1
 935      */
 936     public void setName(String name) {
 937         String oldName;
 938         synchronized(getObjectLock()) {
 939             oldName = this.name;
 940             this.name = name;
 941             nameExplicitlySet = true;
 942         }
 943         firePropertyChange("name", oldName, name);
 944     }
 945 
 946     /**
 947      * Gets the parent of this component.
 948      * @return the parent container of this component
 949      * @since JDK1.0
 950      */
 951     public Container getParent() {
 952         return getParent_NoClientCode();
 953     }
 954 
 955     // NOTE: This method may be called by privileged threads.
 956     //       This functionality is implemented in a package-private method
 957     //       to insure that it cannot be overridden by client subclasses.
 958     //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
 959     final Container getParent_NoClientCode() {
 960         return parent;
 961     }
 962 
 963     // This method is overriden in the Window class to return null,
 964     //    because the parent field of the Window object contains
 965     //    the owner of the window, not its parent.
 966     Container getContainer() {
 967         return getParent();
 968     }
 969 
 970     /**
 971      * @deprecated As of JDK version 1.1,
 972      * programs should not directly manipulate peers;
 973      * replaced by <code>boolean isDisplayable()</code>.
 974      */
 975     @Deprecated
 976     public ComponentPeer getPeer() {
 977         return peer;
 978     }
 979 
 980     /**
 981      * Associate a <code>DropTarget</code> with this component.
 982      * The <code>Component</code> will receive drops only if it
 983      * is enabled.
 984      *
 985      * @see #isEnabled
 986      * @param dt The DropTarget
 987      */
 988 
 989     public synchronized void setDropTarget(DropTarget dt) {
 990         if (dt == dropTarget || (dropTarget != null && dropTarget.equals(dt)))
 991             return;
 992 
 993         DropTarget old;
 994 
 995         if ((old = dropTarget) != null) {
 996             if (peer != null) dropTarget.removeNotify(peer);
 997 
 998             DropTarget t = dropTarget;
 999 
1000             dropTarget = null;
1001 
1002             try {
1003                 t.setComponent(null);
1004             } catch (IllegalArgumentException iae) {
1005                 // ignore it.
1006             }
1007         }
1008 
1009         // if we have a new one, and we have a peer, add it!
1010 
1011         if ((dropTarget = dt) != null) {
1012             try {
1013                 dropTarget.setComponent(this);
1014                 if (peer != null) dropTarget.addNotify(peer);
1015             } catch (IllegalArgumentException iae) {
1016                 if (old != null) {
1017                     try {
1018                         old.setComponent(this);
1019                         if (peer != null) dropTarget.addNotify(peer);
1020                     } catch (IllegalArgumentException iae1) {
1021                         // ignore it!
1022                     }
1023                 }
1024             }
1025         }
1026     }
1027 
1028     /**
1029      * Gets the <code>DropTarget</code> associated with this
1030      * <code>Component</code>.
1031      */
1032 
1033     public synchronized DropTarget getDropTarget() { return dropTarget; }
1034 
1035     /**
1036      * Gets the <code>GraphicsConfiguration</code> associated with this
1037      * <code>Component</code>.
1038      * If the <code>Component</code> has not been assigned a specific
1039      * <code>GraphicsConfiguration</code>,
1040      * the <code>GraphicsConfiguration</code> of the
1041      * <code>Component</code> object's top-level container is
1042      * returned.
1043      * If the <code>Component</code> has been created, but not yet added
1044      * to a <code>Container</code>, this method returns <code>null</code>.
1045      *
1046      * @return the <code>GraphicsConfiguration</code> used by this
1047      *          <code>Component</code> or <code>null</code>
1048      * @since 1.3
1049      */
1050     public GraphicsConfiguration getGraphicsConfiguration() {
1051         synchronized(getTreeLock()) {
1052             return getGraphicsConfiguration_NoClientCode();
1053         }
1054     }
1055 
1056     final GraphicsConfiguration getGraphicsConfiguration_NoClientCode() {
1057         return graphicsConfig;
1058     }
1059 
1060     void setGraphicsConfiguration(GraphicsConfiguration gc) {
1061         synchronized(getTreeLock()) {
1062             if (updateGraphicsData(gc)) {
1063                 removeNotify();
1064                 addNotify();
1065             }
1066         }
1067     }
1068 
1069     boolean updateGraphicsData(GraphicsConfiguration gc) {
1070         checkTreeLock();
1071 
1072         graphicsConfig = gc;
1073 
1074         ComponentPeer peer = getPeer();
1075         if (peer != null) {
1076             return peer.updateGraphicsData(gc);
1077         }
1078         return false;
1079     }
1080 
1081     /**
1082      * Checks that this component's <code>GraphicsDevice</code>
1083      * <code>idString</code> matches the string argument.
1084      */
1085     void checkGD(String stringID) {
1086         if (graphicsConfig != null) {
1087             if (!graphicsConfig.getDevice().getIDstring().equals(stringID)) {
1088                 throw new IllegalArgumentException(
1089                                                    "adding a container to a container on a different GraphicsDevice");
1090             }
1091         }
1092     }
1093 
1094     /**
1095      * Gets this component's locking object (the object that owns the thread
1096      * synchronization monitor) for AWT component-tree and layout
1097      * operations.
1098      * @return this component's locking object
1099      */
1100     public final Object getTreeLock() {
1101         return LOCK;
1102     }
1103 
1104     final void checkTreeLock() {
1105         if (!Thread.holdsLock(getTreeLock())) {
1106             throw new IllegalStateException("This function should be called while holding treeLock");
1107         }
1108     }
1109 
1110     /**
1111      * Gets the toolkit of this component. Note that
1112      * the frame that contains a component controls which
1113      * toolkit is used by that component. Therefore if the component
1114      * is moved from one frame to another, the toolkit it uses may change.
1115      * @return  the toolkit of this component
1116      * @since JDK1.0
1117      */
1118     public Toolkit getToolkit() {
1119         return getToolkitImpl();
1120     }
1121 
1122     /*
1123      * This is called by the native code, so client code can't
1124      * be called on the toolkit thread.
1125      */
1126     final Toolkit getToolkitImpl() {
1127         ComponentPeer peer = this.peer;
1128         if ((peer != null) && ! (peer instanceof LightweightPeer)){
1129             return peer.getToolkit();
1130         }
1131         Container parent = this.parent;
1132         if (parent != null) {
1133             return parent.getToolkitImpl();
1134         }
1135         return Toolkit.getDefaultToolkit();
1136     }
1137 
1138     /**
1139      * Determines whether this component is valid. A component is valid
1140      * when it is correctly sized and positioned within its parent
1141      * container and all its children are also valid.
1142      * In order to account for peers' size requirements, components are invalidated
1143      * before they are first shown on the screen. By the time the parent container
1144      * is fully realized, all its components will be valid.
1145      * @return <code>true</code> if the component is valid, <code>false</code>
1146      * otherwise
1147      * @see #validate
1148      * @see #invalidate
1149      * @since JDK1.0
1150      */
1151     public boolean isValid() {
1152         return (peer != null) && valid;
1153     }
1154 
1155     /**
1156      * Determines whether this component is displayable. A component is
1157      * displayable when it is connected to a native screen resource.
1158      * <p>
1159      * A component is made displayable either when it is added to
1160      * a displayable containment hierarchy or when its containment
1161      * hierarchy is made displayable.
1162      * A containment hierarchy is made displayable when its ancestor
1163      * window is either packed or made visible.
1164      * <p>
1165      * A component is made undisplayable either when it is removed from
1166      * a displayable containment hierarchy or when its containment hierarchy
1167      * is made undisplayable.  A containment hierarchy is made
1168      * undisplayable when its ancestor window is disposed.
1169      *
1170      * @return <code>true</code> if the component is displayable,
1171      * <code>false</code> otherwise
1172      * @see Container#add(Component)
1173      * @see Window#pack
1174      * @see Window#show
1175      * @see Container#remove(Component)
1176      * @see Window#dispose
1177      * @since 1.2
1178      */
1179     public boolean isDisplayable() {
1180         return getPeer() != null;
1181     }
1182 
1183     /**
1184      * Determines whether this component should be visible when its
1185      * parent is visible. Components are
1186      * initially visible, with the exception of top level components such
1187      * as <code>Frame</code> objects.
1188      * @return <code>true</code> if the component is visible,
1189      * <code>false</code> otherwise
1190      * @see #setVisible
1191      * @since JDK1.0
1192      */
1193     @Transient
1194     public boolean isVisible() {
1195         return isVisible_NoClientCode();
1196     }
1197     final boolean isVisible_NoClientCode() {
1198         return visible;
1199     }
1200 
1201     /**
1202      * Determines whether this component will be displayed on the screen.
1203      * @return <code>true</code> if the component and all of its ancestors
1204      *          until a toplevel window or null parent are visible,
1205      *          <code>false</code> otherwise
1206      */
1207     boolean isRecursivelyVisible() {
1208         return visible && (parent == null || parent.isRecursivelyVisible());
1209     }
1210 
1211     /**
1212      * Translates absolute coordinates into coordinates in the coordinate
1213      * space of this component.
1214      */
1215     Point pointRelativeToComponent(Point absolute) {
1216         Point compCoords = getLocationOnScreen();
1217         return new Point(absolute.x - compCoords.x,
1218                          absolute.y - compCoords.y);
1219     }
1220 
1221     /**
1222      * Assuming that mouse location is stored in PointerInfo passed
1223      * to this method, it finds a Component that is in the same
1224      * Window as this Component and is located under the mouse pointer.
1225      * If no such Component exists, null is returned.
1226      * NOTE: this method should be called under the protection of
1227      * tree lock, as it is done in Component.getMousePosition() and
1228      * Container.getMousePosition(boolean).
1229      */
1230     Component findUnderMouseInWindow(PointerInfo pi) {
1231         if (!isShowing()) {
1232             return null;
1233         }
1234         Window win = getContainingWindow();
1235         if (!Toolkit.getDefaultToolkit().getMouseInfoPeer().isWindowUnderMouse(win)) {
1236             return null;
1237         }
1238         final boolean INCLUDE_DISABLED = true;
1239         Point relativeToWindow = win.pointRelativeToComponent(pi.getLocation());
1240         Component inTheSameWindow = win.findComponentAt(relativeToWindow.x,
1241                                                         relativeToWindow.y,
1242                                                         INCLUDE_DISABLED);
1243         return inTheSameWindow;
1244     }
1245 
1246     /**
1247      * Returns the position of the mouse pointer in this <code>Component</code>'s
1248      * coordinate space if the <code>Component</code> is directly under the mouse
1249      * pointer, otherwise returns <code>null</code>.
1250      * If the <code>Component</code> is not showing on the screen, this method
1251      * returns <code>null</code> even if the mouse pointer is above the area
1252      * where the <code>Component</code> would be displayed.
1253      * If the <code>Component</code> is partially or fully obscured by other
1254      * <code>Component</code>s or native windows, this method returns a non-null
1255      * value only if the mouse pointer is located above the unobscured part of the
1256      * <code>Component</code>.
1257      * <p>
1258      * For <code>Container</code>s it returns a non-null value if the mouse is
1259      * above the <code>Container</code> itself or above any of its descendants.
1260      * Use {@link Container#getMousePosition(boolean)} if you need to exclude children.
1261      * <p>
1262      * Sometimes the exact mouse coordinates are not important, and the only thing
1263      * that matters is whether a specific <code>Component</code> is under the mouse
1264      * pointer. If the return value of this method is <code>null</code>, mouse
1265      * pointer is not directly above the <code>Component</code>.
1266      *
1267      * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true
1268      * @see       #isShowing
1269      * @see       Container#getMousePosition
1270      * @return    mouse coordinates relative to this <code>Component</code>, or null
1271      * @since     1.5
1272      */
1273     public Point getMousePosition() throws HeadlessException {
1274         if (GraphicsEnvironment.isHeadless()) {
1275             throw new HeadlessException();
1276         }
1277 
1278         PointerInfo pi = (PointerInfo)java.security.AccessController.doPrivileged(
1279                                                                                   new java.security.PrivilegedAction() {
1280                                                                                       public Object run() {
1281                                                                                           return MouseInfo.getPointerInfo();
1282                                                                                       }
1283                                                                                   }
1284                                                                                   );
1285 
1286         synchronized (getTreeLock()) {
1287             Component inTheSameWindow = findUnderMouseInWindow(pi);
1288             if (!isSameOrAncestorOf(inTheSameWindow, true)) {
1289                 return null;
1290             }
1291             return pointRelativeToComponent(pi.getLocation());
1292         }
1293     }
1294 
1295     /**
1296      * Overridden in Container. Must be called under TreeLock.
1297      */
1298     boolean isSameOrAncestorOf(Component comp, boolean allowChildren) {
1299         return comp == this;
1300     }
1301 
1302     /**
1303      * Determines whether this component is showing on screen. This means
1304      * that the component must be visible, and it must be in a container
1305      * that is visible and showing.
1306      * <p>
1307      * <strong>Note:</strong> sometimes there is no way to detect whether the
1308      * {@code Component} is actually visible to the user.  This can happen when:
1309      * <ul>
1310      * <li>the component has been added to a visible {@code ScrollPane} but
1311      * the {@code Component} is not currently in the scroll pane's view port.
1312      * <li>the {@code Component} is obscured by another {@code Component} or
1313      * {@code Container}.
1314      * </ul>
1315      * @return <code>true</code> if the component is showing,
1316      *          <code>false</code> otherwise
1317      * @see #setVisible
1318      * @since JDK1.0
1319      */
1320     public boolean isShowing() {
1321         if (visible && (peer != null)) {
1322             Container parent = this.parent;
1323             return (parent == null) || parent.isShowing();
1324         }
1325         return false;
1326     }
1327 
1328     /**
1329      * Determines whether this component is enabled. An enabled component
1330      * can respond to user input and generate events. Components are
1331      * enabled initially by default. A component may be enabled or disabled by
1332      * calling its <code>setEnabled</code> method.
1333      * @return <code>true</code> if the component is enabled,
1334      *          <code>false</code> otherwise
1335      * @see #setEnabled
1336      * @since JDK1.0
1337      */
1338     public boolean isEnabled() {
1339         return isEnabledImpl();
1340     }
1341 
1342     /*
1343      * This is called by the native code, so client code can't
1344      * be called on the toolkit thread.
1345      */
1346     final boolean isEnabledImpl() {
1347         return enabled;
1348     }
1349 
1350     /**
1351      * Enables or disables this component, depending on the value of the
1352      * parameter <code>b</code>. An enabled component can respond to user
1353      * input and generate events. Components are enabled initially by default.
1354      *
1355      * <p>Note: Disabling a lightweight component does not prevent it from
1356      * receiving MouseEvents.
1357      * <p>Note: Disabling a heavyweight container prevents all components
1358      * in this container from receiving any input events.  But disabling a
1359      * lightweight container affects only this container.
1360      *
1361      * @param     b   If <code>true</code>, this component is
1362      *            enabled; otherwise this component is disabled
1363      * @see #isEnabled
1364      * @see #isLightweight
1365      * @since JDK1.1
1366      */
1367     public void setEnabled(boolean b) {
1368         enable(b);
1369     }
1370 
1371     /**
1372      * @deprecated As of JDK version 1.1,
1373      * replaced by <code>setEnabled(boolean)</code>.
1374      */
1375     @Deprecated
1376     public void enable() {
1377         if (!enabled) {
1378             synchronized (getTreeLock()) {
1379                 enabled = true;
1380                 ComponentPeer peer = this.peer;
1381                 if (peer != null) {
1382                     peer.setEnabled(true);
1383                     if (visible) {
1384                         updateCursorImmediately();
1385                     }
1386                 }
1387             }
1388             if (accessibleContext != null) {
1389                 accessibleContext.firePropertyChange(
1390                                                      AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
1391                                                      null, AccessibleState.ENABLED);
1392             }
1393         }
1394     }
1395 
1396     /**
1397      * @deprecated As of JDK version 1.1,
1398      * replaced by <code>setEnabled(boolean)</code>.
1399      */
1400     @Deprecated
1401     public void enable(boolean b) {
1402         if (b) {
1403             enable();
1404         } else {
1405             disable();
1406         }
1407     }
1408 
1409     /**
1410      * @deprecated As of JDK version 1.1,
1411      * replaced by <code>setEnabled(boolean)</code>.
1412      */
1413     @Deprecated
1414     public void disable() {
1415         if (enabled) {
1416             KeyboardFocusManager.clearMostRecentFocusOwner(this);
1417             synchronized (getTreeLock()) {
1418                 enabled = false;
1419                 // A disabled lw container is allowed to contain a focus owner.
1420                 if ((isFocusOwner() || (containsFocus() && !isLightweight())) &&
1421                     KeyboardFocusManager.isAutoFocusTransferEnabled())
1422                 {
1423                     // Don't clear the global focus owner. If transferFocus
1424                     // fails, we want the focus to stay on the disabled
1425                     // Component so that keyboard traversal, et. al. still
1426                     // makes sense to the user.
1427                     transferFocus(false);
1428                 }
1429                 ComponentPeer peer = this.peer;
1430                 if (peer != null) {
1431                     peer.setEnabled(false);
1432                     if (visible) {
1433                         updateCursorImmediately();
1434                     }
1435                 }
1436             }
1437             if (accessibleContext != null) {
1438                 accessibleContext.firePropertyChange(
1439                                                      AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
1440                                                      null, AccessibleState.ENABLED);
1441             }
1442         }
1443     }
1444 
1445     /**
1446      * Returns true if this component is painted to an offscreen image
1447      * ("buffer") that's copied to the screen later.  Component
1448      * subclasses that support double buffering should override this
1449      * method to return true if double buffering is enabled.
1450      *
1451      * @return false by default
1452      */
1453     public boolean isDoubleBuffered() {
1454         return false;
1455     }
1456 
1457     /**
1458      * Enables or disables input method support for this component. If input
1459      * method support is enabled and the component also processes key events,
1460      * incoming events are offered to
1461      * the current input method and will only be processed by the component or
1462      * dispatched to its listeners if the input method does not consume them.
1463      * By default, input method support is enabled.
1464      *
1465      * @param enable true to enable, false to disable
1466      * @see #processKeyEvent
1467      * @since 1.2
1468      */
1469     public void enableInputMethods(boolean enable) {
1470         if (enable) {
1471             if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0)
1472                 return;
1473 
1474             // If this component already has focus, then activate the
1475             // input method by dispatching a synthesized focus gained
1476             // event.
1477             if (isFocusOwner()) {
1478                 InputContext inputContext = getInputContext();
1479                 if (inputContext != null) {
1480                     FocusEvent focusGainedEvent =
1481                         new FocusEvent(this, FocusEvent.FOCUS_GAINED);
1482                     inputContext.dispatchEvent(focusGainedEvent);
1483                 }
1484             }
1485 
1486             eventMask |= AWTEvent.INPUT_METHODS_ENABLED_MASK;
1487         } else {
1488             if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) {
1489                 InputContext inputContext = getInputContext();
1490                 if (inputContext != null) {
1491                     inputContext.endComposition();
1492                     inputContext.removeNotify(this);
1493                 }
1494             }
1495             eventMask &= ~AWTEvent.INPUT_METHODS_ENABLED_MASK;
1496         }
1497     }
1498 
1499     /**
1500      * Shows or hides this component depending on the value of parameter
1501      * <code>b</code>.
1502      * <p>
1503      * This method changes layout-related information, and therefore,
1504      * invalidates the component hierarchy.
1505      *
1506      * @param b  if <code>true</code>, shows this component;
1507      * otherwise, hides this component
1508      * @see #isVisible
1509      * @see #invalidate
1510      * @since JDK1.1
1511      */
1512     public void setVisible(boolean b) {
1513         show(b);
1514     }
1515 
1516     /**
1517      * @deprecated As of JDK version 1.1,
1518      * replaced by <code>setVisible(boolean)</code>.
1519      */
1520     @Deprecated
1521     public void show() {
1522         if (!visible) {
1523             synchronized (getTreeLock()) {
1524                 visible = true;
1525                 mixOnShowing();
1526                 ComponentPeer peer = this.peer;
1527                 if (peer != null) {
1528                     peer.setVisible(true);
1529                     createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,
1530                                           this, parent,
1531                                           HierarchyEvent.SHOWING_CHANGED,
1532                                           Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
1533                     if (peer instanceof LightweightPeer) {
1534                         repaint();
1535                     }
1536                     updateCursorImmediately();
1537                 }
1538 
1539                 if (componentListener != null ||
1540                     (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||
1541                     Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) {
1542                     ComponentEvent e = new ComponentEvent(this,
1543                                                           ComponentEvent.COMPONENT_SHOWN);
1544                     Toolkit.getEventQueue().postEvent(e);
1545                 }
1546             }
1547             Container parent = this.parent;
1548             if (parent != null) {
1549                 parent.invalidate();
1550             }
1551         }
1552     }
1553 
1554     /**
1555      * @deprecated As of JDK version 1.1,
1556      * replaced by <code>setVisible(boolean)</code>.
1557      */
1558     @Deprecated
1559     public void show(boolean b) {
1560         if (b) {
1561             show();
1562         } else {
1563             hide();
1564         }
1565     }
1566 
1567     boolean containsFocus() {
1568         return isFocusOwner();
1569     }
1570 
1571     void clearMostRecentFocusOwnerOnHide() {
1572         KeyboardFocusManager.clearMostRecentFocusOwner(this);
1573     }
1574 
1575     void clearCurrentFocusCycleRootOnHide() {
1576         /* do nothing */
1577     }
1578 
1579     /**
1580      * @deprecated As of JDK version 1.1,
1581      * replaced by <code>setVisible(boolean)</code>.
1582      */
1583     @Deprecated
1584     public void hide() {
1585         isPacked = false;
1586 
1587         if (visible) {
1588             clearCurrentFocusCycleRootOnHide();
1589             clearMostRecentFocusOwnerOnHide();
1590             synchronized (getTreeLock()) {
1591                 visible = false;
1592                 mixOnHiding(isLightweight());
1593                 if (containsFocus() && KeyboardFocusManager.isAutoFocusTransferEnabled()) {
1594                     transferFocus(true);
1595                 }
1596                 ComponentPeer peer = this.peer;
1597                 if (peer != null) {
1598                     peer.setVisible(false);
1599                     createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,
1600                                           this, parent,
1601                                           HierarchyEvent.SHOWING_CHANGED,
1602                                           Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
1603                     if (peer instanceof LightweightPeer) {
1604                         repaint();
1605                     }
1606                     updateCursorImmediately();
1607                 }
1608                 if (componentListener != null ||
1609                     (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||
1610                     Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) {
1611                     ComponentEvent e = new ComponentEvent(this,
1612                                                           ComponentEvent.COMPONENT_HIDDEN);
1613                     Toolkit.getEventQueue().postEvent(e);
1614                 }
1615             }
1616             Container parent = this.parent;
1617             if (parent != null) {
1618                 parent.invalidate();
1619             }
1620         }
1621     }
1622 
1623     /**
1624      * Gets the foreground color of this component.
1625      * @return this component's foreground color; if this component does
1626      * not have a foreground color, the foreground color of its parent
1627      * is returned
1628      * @see #setForeground
1629      * @since JDK1.0
1630      * @beaninfo
1631      *       bound: true
1632      */
1633     @Transient
1634     public Color getForeground() {
1635         Color foreground = this.foreground;
1636         if (foreground != null) {
1637             return foreground;
1638         }
1639         Container parent = this.parent;
1640         return (parent != null) ? parent.getForeground() : null;
1641     }
1642 
1643     /**
1644      * Sets the foreground color of this component.
1645      * @param c the color to become this component's
1646      *          foreground color; if this parameter is <code>null</code>
1647      *          then this component will inherit
1648      *          the foreground color of its parent
1649      * @see #getForeground
1650      * @since JDK1.0
1651      */
1652     public void setForeground(Color c) {
1653         Color oldColor = foreground;
1654         ComponentPeer peer = this.peer;
1655         foreground = c;
1656         if (peer != null) {
1657             c = getForeground();
1658             if (c != null) {
1659                 peer.setForeground(c);
1660             }
1661         }
1662         // This is a bound property, so report the change to
1663         // any registered listeners.  (Cheap if there are none.)
1664         firePropertyChange("foreground", oldColor, c);
1665     }
1666 
1667     /**
1668      * Returns whether the foreground color has been explicitly set for this
1669      * Component. If this method returns <code>false</code>, this Component is
1670      * inheriting its foreground color from an ancestor.
1671      *
1672      * @return <code>true</code> if the foreground color has been explicitly
1673      *         set for this Component; <code>false</code> otherwise.
1674      * @since 1.4
1675      */
1676     public boolean isForegroundSet() {
1677         return (foreground != null);
1678     }
1679 
1680     /**
1681      * Gets the background color of this component.
1682      * @return this component's background color; if this component does
1683      *          not have a background color,
1684      *          the background color of its parent is returned
1685      * @see #setBackground
1686      * @since JDK1.0
1687      */
1688     @Transient
1689     public Color getBackground() {
1690         Color background = this.background;
1691         if (background != null) {
1692             return background;
1693         }
1694         Container parent = this.parent;
1695         return (parent != null) ? parent.getBackground() : null;
1696     }
1697 
1698     /**
1699      * Sets the background color of this component.
1700      * <p>
1701      * The background color affects each component differently and the
1702      * parts of the component that are affected by the background color
1703      * may differ between operating systems.
1704      *
1705      * @param c the color to become this component's color;
1706      *          if this parameter is <code>null</code>, then this
1707      *          component will inherit the background color of its parent
1708      * @see #getBackground
1709      * @since JDK1.0
1710      * @beaninfo
1711      *       bound: true
1712      */
1713     public void setBackground(Color c) {
1714         Color oldColor = background;
1715         ComponentPeer peer = this.peer;
1716         background = c;
1717         if (peer != null) {
1718             c = getBackground();
1719             if (c != null) {
1720                 peer.setBackground(c);
1721             }
1722         }
1723         // This is a bound property, so report the change to
1724         // any registered listeners.  (Cheap if there are none.)
1725         firePropertyChange("background", oldColor, c);
1726     }
1727 
1728     /**
1729      * Returns whether the background color has been explicitly set for this
1730      * Component. If this method returns <code>false</code>, this Component is
1731      * inheriting its background color from an ancestor.
1732      *
1733      * @return <code>true</code> if the background color has been explicitly
1734      *         set for this Component; <code>false</code> otherwise.
1735      * @since 1.4
1736      */
1737     public boolean isBackgroundSet() {
1738         return (background != null);
1739     }
1740 
1741     /**
1742      * Gets the font of this component.
1743      * @return this component's font; if a font has not been set
1744      * for this component, the font of its parent is returned
1745      * @see #setFont
1746      * @since JDK1.0
1747      */
1748     @Transient
1749     public Font getFont() {
1750         return getFont_NoClientCode();
1751     }
1752 
1753     // NOTE: This method may be called by privileged threads.
1754     //       This functionality is implemented in a package-private method
1755     //       to insure that it cannot be overridden by client subclasses.
1756     //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
1757     final Font getFont_NoClientCode() {
1758         Font font = this.font;
1759         if (font != null) {
1760             return font;
1761         }
1762         Container parent = this.parent;
1763         return (parent != null) ? parent.getFont_NoClientCode() : null;
1764     }
1765 
1766     /**
1767      * Sets the font of this component.
1768      * <p>
1769      * This method changes layout-related information, and therefore,
1770      * invalidates the component hierarchy.
1771      *
1772      * @param f the font to become this component's font;
1773      *          if this parameter is <code>null</code> then this
1774      *          component will inherit the font of its parent
1775      * @see #getFont
1776      * @see #invalidate
1777      * @since JDK1.0
1778      * @beaninfo
1779      *       bound: true
1780      */
1781     public void setFont(Font f) {
1782         Font oldFont, newFont;
1783         synchronized(getTreeLock()) {
1784             synchronized (this) {
1785                 oldFont = font;
1786                 newFont = font = f;
1787             }
1788             ComponentPeer peer = this.peer;
1789             if (peer != null) {
1790                 f = getFont();
1791                 if (f != null) {
1792                     peer.setFont(f);
1793                     peerFont = f;
1794                 }
1795             }
1796         }
1797         // This is a bound property, so report the change to
1798         // any registered listeners.  (Cheap if there are none.)
1799         firePropertyChange("font", oldFont, newFont);
1800 
1801         // This could change the preferred size of the Component.
1802         // Fix for 6213660. Should compare old and new fonts and do not
1803         // call invalidate() if they are equal.
1804         if (f != oldFont && (oldFont == null ||
1805                                       !oldFont.equals(f))) {
1806             invalidateIfValid();
1807         }
1808     }
1809 
1810     /**
1811      * Returns whether the font has been explicitly set for this Component. If
1812      * this method returns <code>false</code>, this Component is inheriting its
1813      * font from an ancestor.
1814      *
1815      * @return <code>true</code> if the font has been explicitly set for this
1816      *         Component; <code>false</code> otherwise.
1817      * @since 1.4
1818      */
1819     public boolean isFontSet() {
1820         return (font != null);
1821     }
1822 
1823     /**
1824      * Gets the locale of this component.
1825      * @return this component's locale; if this component does not
1826      *          have a locale, the locale of its parent is returned
1827      * @see #setLocale
1828      * @exception IllegalComponentStateException if the <code>Component</code>
1829      *          does not have its own locale and has not yet been added to
1830      *          a containment hierarchy such that the locale can be determined
1831      *          from the containing parent
1832      * @since  JDK1.1
1833      */
1834     public Locale getLocale() {
1835         Locale locale = this.locale;
1836         if (locale != null) {
1837             return locale;
1838         }
1839         Container parent = this.parent;
1840 
1841         if (parent == null) {
1842             throw new IllegalComponentStateException("This component must have a parent in order to determine its locale");
1843         } else {
1844             return parent.getLocale();
1845         }
1846     }
1847 
1848     /**
1849      * Sets the locale of this component.  This is a bound property.
1850      * <p>
1851      * This method changes layout-related information, and therefore,
1852      * invalidates the component hierarchy.
1853      *
1854      * @param l the locale to become this component's locale
1855      * @see #getLocale
1856      * @see #invalidate
1857      * @since JDK1.1
1858      */
1859     public void setLocale(Locale l) {
1860         Locale oldValue = locale;
1861         locale = l;
1862 
1863         // This is a bound property, so report the change to
1864         // any registered listeners.  (Cheap if there are none.)
1865         firePropertyChange("locale", oldValue, l);
1866 
1867         // This could change the preferred size of the Component.
1868         invalidateIfValid();
1869     }
1870 
1871     /**
1872      * Gets the instance of <code>ColorModel</code> used to display
1873      * the component on the output device.
1874      * @return the color model used by this component
1875      * @see java.awt.image.ColorModel
1876      * @see java.awt.peer.ComponentPeer#getColorModel()
1877      * @see Toolkit#getColorModel()
1878      * @since JDK1.0
1879      */
1880     public ColorModel getColorModel() {
1881         ComponentPeer peer = this.peer;
1882         if ((peer != null) && ! (peer instanceof LightweightPeer)) {
1883             return peer.getColorModel();
1884         } else if (GraphicsEnvironment.isHeadless()) {
1885             return ColorModel.getRGBdefault();
1886         } // else
1887         return getToolkit().getColorModel();
1888     }
1889 
1890     /**
1891      * Gets the location of this component in the form of a
1892      * point specifying the component's top-left corner.
1893      * The location will be relative to the parent's coordinate space.
1894      * <p>
1895      * Due to the asynchronous nature of native event handling, this
1896      * method can return outdated values (for instance, after several calls
1897      * of <code>setLocation()</code> in rapid succession).  For this
1898      * reason, the recommended method of obtaining a component's position is
1899      * within <code>java.awt.event.ComponentListener.componentMoved()</code>,
1900      * which is called after the operating system has finished moving the
1901      * component.
1902      * </p>
1903      * @return an instance of <code>Point</code> representing
1904      *          the top-left corner of the component's bounds in
1905      *          the coordinate space of the component's parent
1906      * @see #setLocation
1907      * @see #getLocationOnScreen
1908      * @since JDK1.1
1909      */
1910     public Point getLocation() {
1911         return location();
1912     }
1913 
1914     /**
1915      * Gets the location of this component in the form of a point
1916      * specifying the component's top-left corner in the screen's
1917      * coordinate space.
1918      * @return an instance of <code>Point</code> representing
1919      *          the top-left corner of the component's bounds in the
1920      *          coordinate space of the screen
1921      * @throws <code>IllegalComponentStateException</code> if the
1922      *          component is not showing on the screen
1923      * @see #setLocation
1924      * @see #getLocation
1925      */
1926     public Point getLocationOnScreen() {
1927         synchronized (getTreeLock()) {
1928             return getLocationOnScreen_NoTreeLock();
1929         }
1930     }
1931 
1932     /*
1933      * a package private version of getLocationOnScreen
1934      * used by GlobalCursormanager to update cursor
1935      */
1936     final Point getLocationOnScreen_NoTreeLock() {
1937 
1938         if (peer != null && isShowing()) {
1939             if (peer instanceof LightweightPeer) {
1940                 // lightweight component location needs to be translated
1941                 // relative to a native component.
1942                 Container host = getNativeContainer();
1943                 Point pt = host.peer.getLocationOnScreen();
1944                 for(Component c = this; c != host; c = c.getParent()) {
1945                     pt.x += c.x;
1946                     pt.y += c.y;
1947                 }
1948                 return pt;
1949             } else {
1950                 Point pt = peer.getLocationOnScreen();
1951                 return pt;
1952             }
1953         } else {
1954             throw new IllegalComponentStateException("component must be showing on the screen to determine its location");
1955         }
1956     }
1957 
1958 
1959     /**
1960      * @deprecated As of JDK version 1.1,
1961      * replaced by <code>getLocation()</code>.
1962      */
1963     @Deprecated
1964     public Point location() {
1965         return location_NoClientCode();
1966     }
1967 
1968     private Point location_NoClientCode() {
1969         return new Point(x, y);
1970     }
1971 
1972     /**
1973      * Moves this component to a new location. The top-left corner of
1974      * the new location is specified by the <code>x</code> and <code>y</code>
1975      * parameters in the coordinate space of this component's parent.
1976      * <p>
1977      * This method changes layout-related information, and therefore,
1978      * invalidates the component hierarchy.
1979      *
1980      * @param x the <i>x</i>-coordinate of the new location's
1981      *          top-left corner in the parent's coordinate space
1982      * @param y the <i>y</i>-coordinate of the new location's
1983      *          top-left corner in the parent's coordinate space
1984      * @see #getLocation
1985      * @see #setBounds
1986      * @see #invalidate
1987      * @since JDK1.1
1988      */
1989     public void setLocation(int x, int y) {
1990         move(x, y);
1991     }
1992 
1993     /**
1994      * @deprecated As of JDK version 1.1,
1995      * replaced by <code>setLocation(int, int)</code>.
1996      */
1997     @Deprecated
1998     public void move(int x, int y) {
1999         synchronized(getTreeLock()) {
2000             setBoundsOp(ComponentPeer.SET_LOCATION);
2001             setBounds(x, y, width, height);
2002         }
2003     }
2004 
2005     /**
2006      * Moves this component to a new location. The top-left corner of
2007      * the new location is specified by point <code>p</code>. Point
2008      * <code>p</code> is given in the parent's coordinate space.
2009      * <p>
2010      * This method changes layout-related information, and therefore,
2011      * invalidates the component hierarchy.
2012      *
2013      * @param p the point defining the top-left corner
2014      *          of the new location, given in the coordinate space of this
2015      *          component's parent
2016      * @see #getLocation
2017      * @see #setBounds
2018      * @see #invalidate
2019      * @since JDK1.1
2020      */
2021     public void setLocation(Point p) {
2022         setLocation(p.x, p.y);
2023     }
2024 
2025     /**
2026      * Returns the size of this component in the form of a
2027      * <code>Dimension</code> object. The <code>height</code>
2028      * field of the <code>Dimension</code> object contains
2029      * this component's height, and the <code>width</code>
2030      * field of the <code>Dimension</code> object contains
2031      * this component's width.
2032      * @return a <code>Dimension</code> object that indicates the
2033      *          size of this component
2034      * @see #setSize
2035      * @since JDK1.1
2036      */
2037     public Dimension getSize() {
2038         return size();
2039     }
2040 
2041     /**
2042      * @deprecated As of JDK version 1.1,
2043      * replaced by <code>getSize()</code>.
2044      */
2045     @Deprecated
2046     public Dimension size() {
2047         return new Dimension(width, height);
2048     }
2049 
2050     /**
2051      * Resizes this component so that it has width <code>width</code>
2052      * and height <code>height</code>.
2053      * <p>
2054      * This method changes layout-related information, and therefore,
2055      * invalidates the component hierarchy.
2056      *
2057      * @param width the new width of this component in pixels
2058      * @param height the new height of this component in pixels
2059      * @see #getSize
2060      * @see #setBounds
2061      * @see #invalidate
2062      * @since JDK1.1
2063      */
2064     public void setSize(int width, int height) {
2065         resize(width, height);
2066     }
2067 
2068     /**
2069      * @deprecated As of JDK version 1.1,
2070      * replaced by <code>setSize(int, int)</code>.
2071      */
2072     @Deprecated
2073     public void resize(int width, int height) {
2074         synchronized(getTreeLock()) {
2075             setBoundsOp(ComponentPeer.SET_SIZE);
2076             setBounds(x, y, width, height);
2077         }
2078     }
2079 
2080     /**
2081      * Resizes this component so that it has width <code>d.width</code>
2082      * and height <code>d.height</code>.
2083      * <p>
2084      * This method changes layout-related information, and therefore,
2085      * invalidates the component hierarchy.
2086      *
2087      * @param d the dimension specifying the new size
2088      *          of this component
2089      * @see #setSize
2090      * @see #setBounds
2091      * @see #invalidate
2092      * @since JDK1.1
2093      */
2094     public void setSize(Dimension d) {
2095         resize(d);
2096     }
2097 
2098     /**
2099      * @deprecated As of JDK version 1.1,
2100      * replaced by <code>setSize(Dimension)</code>.
2101      */
2102     @Deprecated
2103     public void resize(Dimension d) {
2104         setSize(d.width, d.height);
2105     }
2106 
2107     /**
2108      * Gets the bounds of this component in the form of a
2109      * <code>Rectangle</code> object. The bounds specify this
2110      * component's width, height, and location relative to
2111      * its parent.
2112      * @return a rectangle indicating this component's bounds
2113      * @see #setBounds
2114      * @see #getLocation
2115      * @see #getSize
2116      */
2117     public Rectangle getBounds() {
2118         return bounds();
2119     }
2120 
2121     /**
2122      * @deprecated As of JDK version 1.1,
2123      * replaced by <code>getBounds()</code>.
2124      */
2125     @Deprecated
2126     public Rectangle bounds() {
2127         return new Rectangle(x, y, width, height);
2128     }
2129 
2130     /**
2131      * Moves and resizes this component. The new location of the top-left
2132      * corner is specified by <code>x</code> and <code>y</code>, and the
2133      * new size is specified by <code>width</code> and <code>height</code>.
2134      * <p>
2135      * This method changes layout-related information, and therefore,
2136      * invalidates the component hierarchy.
2137      *
2138      * @param x the new <i>x</i>-coordinate of this component
2139      * @param y the new <i>y</i>-coordinate of this component
2140      * @param width the new <code>width</code> of this component
2141      * @param height the new <code>height</code> of this
2142      *          component
2143      * @see #getBounds
2144      * @see #setLocation(int, int)
2145      * @see #setLocation(Point)
2146      * @see #setSize(int, int)
2147      * @see #setSize(Dimension)
2148      * @see #invalidate
2149      * @since JDK1.1
2150      */
2151     public void setBounds(int x, int y, int width, int height) {
2152         reshape(x, y, width, height);
2153     }
2154 
2155     /**
2156      * @deprecated As of JDK version 1.1,
2157      * replaced by <code>setBounds(int, int, int, int)</code>.
2158      */
2159     @Deprecated
2160     public void reshape(int x, int y, int width, int height) {
2161         synchronized (getTreeLock()) {
2162             try {
2163                 setBoundsOp(ComponentPeer.SET_BOUNDS);
2164                 boolean resized = (this.width != width) || (this.height != height);
2165                 boolean moved = (this.x != x) || (this.y != y);
2166                 if (!resized && !moved) {
2167                     return;
2168                 }
2169                 int oldX = this.x;
2170                 int oldY = this.y;
2171                 int oldWidth = this.width;
2172                 int oldHeight = this.height;
2173                 this.x = x;
2174                 this.y = y;
2175                 this.width = width;
2176                 this.height = height;
2177 
2178                 if (resized) {
2179                     isPacked = false;
2180                 }
2181 
2182                 boolean needNotify = true;
2183                 mixOnReshaping();
2184                 if (peer != null) {
2185                     // LightwightPeer is an empty stub so can skip peer.reshape
2186                     if (!(peer instanceof LightweightPeer)) {
2187                         reshapeNativePeer(x, y, width, height, getBoundsOp());
2188                         // Check peer actualy changed coordinates
2189                         resized = (oldWidth != this.width) || (oldHeight != this.height);
2190                         moved = (oldX != this.x) || (oldY != this.y);
2191                         // fix for 5025858: do not send ComponentEvents for toplevel
2192                         // windows here as it is done from peer or native code when
2193                         // the window is really resized or moved, otherwise some
2194                         // events may be sent twice
2195                         if (this instanceof Window) {
2196                             needNotify = false;
2197                         }
2198                     }
2199                     if (resized) {
2200                         invalidate();
2201                     }
2202                     if (parent != null) {
2203                         parent.invalidateIfValid();
2204                     }
2205                 }
2206                 if (needNotify) {
2207                     notifyNewBounds(resized, moved);
2208                 }
2209                 repaintParentIfNeeded(oldX, oldY, oldWidth, oldHeight);
2210             } finally {
2211                 setBoundsOp(ComponentPeer.RESET_OPERATION);
2212             }
2213         }
2214     }
2215 
2216     private void repaintParentIfNeeded(int oldX, int oldY, int oldWidth,
2217                                        int oldHeight)
2218     {
2219         if (parent != null && peer instanceof LightweightPeer && isShowing()) {
2220             // Have the parent redraw the area this component occupied.
2221             parent.repaint(oldX, oldY, oldWidth, oldHeight);
2222             // Have the parent redraw the area this component *now* occupies.
2223             repaint();
2224         }
2225     }
2226 
2227     private void reshapeNativePeer(int x, int y, int width, int height, int op) {
2228         // native peer might be offset by more than direct
2229         // parent since parent might be lightweight.
2230         int nativeX = x;
2231         int nativeY = y;
2232         for (Component c = parent;
2233              (c != null) && (c.peer instanceof LightweightPeer);
2234              c = c.parent)
2235         {
2236             nativeX += c.x;
2237             nativeY += c.y;
2238         }
2239         peer.setBounds(nativeX, nativeY, width, height, op);
2240     }
2241 
2242 
2243     private void notifyNewBounds(boolean resized, boolean moved) {
2244         if (componentListener != null
2245             || (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0
2246             || Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK))
2247             {
2248                 if (resized) {
2249                     ComponentEvent e = new ComponentEvent(this,
2250                                                           ComponentEvent.COMPONENT_RESIZED);
2251                     Toolkit.getEventQueue().postEvent(e);
2252                 }
2253                 if (moved) {
2254                     ComponentEvent e = new ComponentEvent(this,
2255                                                           ComponentEvent.COMPONENT_MOVED);
2256                     Toolkit.getEventQueue().postEvent(e);
2257                 }
2258             } else {
2259                 if (this instanceof Container && ((Container)this).countComponents() > 0) {
2260                     boolean enabledOnToolkit =
2261                         Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK);
2262                     if (resized) {
2263 
2264                         ((Container)this).createChildHierarchyEvents(
2265                                                                      HierarchyEvent.ANCESTOR_RESIZED, 0, enabledOnToolkit);
2266                     }
2267                     if (moved) {
2268                         ((Container)this).createChildHierarchyEvents(
2269                                                                      HierarchyEvent.ANCESTOR_MOVED, 0, enabledOnToolkit);
2270                     }
2271                 }
2272                 }
2273     }
2274 
2275     /**
2276      * Moves and resizes this component to conform to the new
2277      * bounding rectangle <code>r</code>. This component's new
2278      * position is specified by <code>r.x</code> and <code>r.y</code>,
2279      * and its new size is specified by <code>r.width</code> and
2280      * <code>r.height</code>
2281      * <p>
2282      * This method changes layout-related information, and therefore,
2283      * invalidates the component hierarchy.
2284      *
2285      * @param r the new bounding rectangle for this component
2286      * @see       #getBounds
2287      * @see       #setLocation(int, int)
2288      * @see       #setLocation(Point)
2289      * @see       #setSize(int, int)
2290      * @see       #setSize(Dimension)
2291      * @see #invalidate
2292      * @since     JDK1.1
2293      */
2294     public void setBounds(Rectangle r) {
2295         setBounds(r.x, r.y, r.width, r.height);
2296     }
2297 
2298 
2299     /**
2300      * Returns the current x coordinate of the components origin.
2301      * This method is preferable to writing
2302      * <code>component.getBounds().x</code>,
2303      * or <code>component.getLocation().x</code> because it doesn't
2304      * cause any heap allocations.
2305      *
2306      * @return the current x coordinate of the components origin
2307      * @since 1.2
2308      */
2309     public int getX() {
2310         return x;
2311     }
2312 
2313 
2314     /**
2315      * Returns the current y coordinate of the components origin.
2316      * This method is preferable to writing
2317      * <code>component.getBounds().y</code>,
2318      * or <code>component.getLocation().y</code> because it
2319      * doesn't cause any heap allocations.
2320      *
2321      * @return the current y coordinate of the components origin
2322      * @since 1.2
2323      */
2324     public int getY() {
2325         return y;
2326     }
2327 
2328 
2329     /**
2330      * Returns the current width of this component.
2331      * This method is preferable to writing
2332      * <code>component.getBounds().width</code>,
2333      * or <code>component.getSize().width</code> because it
2334      * doesn't cause any heap allocations.
2335      *
2336      * @return the current width of this component
2337      * @since 1.2
2338      */
2339     public int getWidth() {
2340         return width;
2341     }
2342 
2343 
2344     /**
2345      * Returns the current height of this component.
2346      * This method is preferable to writing
2347      * <code>component.getBounds().height</code>,
2348      * or <code>component.getSize().height</code> because it
2349      * doesn't cause any heap allocations.
2350      *
2351      * @return the current height of this component
2352      * @since 1.2
2353      */
2354     public int getHeight() {
2355         return height;
2356     }
2357 
2358     /**
2359      * Stores the bounds of this component into "return value" <b>rv</b> and
2360      * return <b>rv</b>.  If rv is <code>null</code> a new
2361      * <code>Rectangle</code> is allocated.
2362      * This version of <code>getBounds</code> is useful if the caller
2363      * wants to avoid allocating a new <code>Rectangle</code> object
2364      * on the heap.
2365      *
2366      * @param rv the return value, modified to the components bounds
2367      * @return rv
2368      */
2369     public Rectangle getBounds(Rectangle rv) {
2370         if (rv == null) {
2371             return new Rectangle(getX(), getY(), getWidth(), getHeight());
2372         }
2373         else {
2374             rv.setBounds(getX(), getY(), getWidth(), getHeight());
2375             return rv;
2376         }
2377     }
2378 
2379     /**
2380      * Stores the width/height of this component into "return value" <b>rv</b>
2381      * and return <b>rv</b>.   If rv is <code>null</code> a new
2382      * <code>Dimension</code> object is allocated.  This version of
2383      * <code>getSize</code> is useful if the caller wants to avoid
2384      * allocating a new <code>Dimension</code> object on the heap.
2385      *
2386      * @param rv the return value, modified to the components size
2387      * @return rv
2388      */
2389     public Dimension getSize(Dimension rv) {
2390         if (rv == null) {
2391             return new Dimension(getWidth(), getHeight());
2392         }
2393         else {
2394             rv.setSize(getWidth(), getHeight());
2395             return rv;
2396         }
2397     }
2398 
2399     /**
2400      * Stores the x,y origin of this component into "return value" <b>rv</b>
2401      * and return <b>rv</b>.   If rv is <code>null</code> a new
2402      * <code>Point</code> is allocated.
2403      * This version of <code>getLocation</code> is useful if the
2404      * caller wants to avoid allocating a new <code>Point</code>
2405      * object on the heap.
2406      *
2407      * @param rv the return value, modified to the components location
2408      * @return rv
2409      */
2410     public Point getLocation(Point rv) {
2411         if (rv == null) {
2412             return new Point(getX(), getY());
2413         }
2414         else {
2415             rv.setLocation(getX(), getY());
2416             return rv;
2417         }
2418     }
2419 
2420     /**
2421      * Returns true if this component is completely opaque, returns
2422      * false by default.
2423      * <p>
2424      * An opaque component paints every pixel within its
2425      * rectangular region. A non-opaque component paints only some of
2426      * its pixels, allowing the pixels underneath it to "show through".
2427      * A component that does not fully paint its pixels therefore
2428      * provides a degree of transparency.
2429      * <p>
2430      * Subclasses that guarantee to always completely paint their
2431      * contents should override this method and return true.
2432      *
2433      * @return true if this component is completely opaque
2434      * @see #isLightweight
2435      * @since 1.2
2436      */
2437     public boolean isOpaque() {
2438         if (getPeer() == null) {
2439             return false;
2440         }
2441         else {
2442             return !isLightweight();
2443         }
2444     }
2445 
2446 
2447     /**
2448      * A lightweight component doesn't have a native toolkit peer.
2449      * Subclasses of <code>Component</code> and <code>Container</code>,
2450      * other than the ones defined in this package like <code>Button</code>
2451      * or <code>Scrollbar</code>, are lightweight.
2452      * All of the Swing components are lightweights.
2453      * <p>
2454      * This method will always return <code>false</code> if this component
2455      * is not displayable because it is impossible to determine the
2456      * weight of an undisplayable component.
2457      *
2458      * @return true if this component has a lightweight peer; false if
2459      *         it has a native peer or no peer
2460      * @see #isDisplayable
2461      * @since 1.2
2462      */
2463     public boolean isLightweight() {
2464         return getPeer() instanceof LightweightPeer;
2465     }
2466 
2467 
2468     /**
2469      * Sets the preferred size of this component to a constant
2470      * value.  Subsequent calls to <code>getPreferredSize</code> will always
2471      * return this value.  Setting the preferred size to <code>null</code>
2472      * restores the default behavior.
2473      *
2474      * @param preferredSize The new preferred size, or null
2475      * @see #getPreferredSize
2476      * @see #isPreferredSizeSet
2477      * @since 1.5
2478      */
2479     public void setPreferredSize(Dimension preferredSize) {
2480         Dimension old;
2481         // If the preferred size was set, use it as the old value, otherwise
2482         // use null to indicate we didn't previously have a set preferred
2483         // size.
2484         if (prefSizeSet) {
2485             old = this.prefSize;
2486         }
2487         else {
2488             old = null;
2489         }
2490         this.prefSize = preferredSize;
2491         prefSizeSet = (preferredSize != null);
2492         firePropertyChange("preferredSize", old, preferredSize);
2493     }
2494 
2495 
2496     /**
2497      * Returns true if the preferred size has been set to a
2498      * non-<code>null</code> value otherwise returns false.
2499      *
2500      * @return true if <code>setPreferredSize</code> has been invoked
2501      *         with a non-null value.
2502      * @since 1.5
2503      */
2504     public boolean isPreferredSizeSet() {
2505         return prefSizeSet;
2506     }
2507 
2508 
2509     /**
2510      * Gets the preferred size of this component.
2511      * @return a dimension object indicating this component's preferred size
2512      * @see #getMinimumSize
2513      * @see LayoutManager
2514      */
2515     public Dimension getPreferredSize() {
2516         return preferredSize();
2517     }
2518 
2519 
2520     /**
2521      * @deprecated As of JDK version 1.1,
2522      * replaced by <code>getPreferredSize()</code>.
2523      */
2524     @Deprecated
2525     public Dimension preferredSize() {
2526         /* Avoid grabbing the lock if a reasonable cached size value
2527          * is available.
2528          */
2529         Dimension dim = prefSize;
2530         if (dim == null || !(isPreferredSizeSet() || isValid())) {
2531             synchronized (getTreeLock()) {
2532                 prefSize = (peer != null) ?
2533                     peer.getPreferredSize() :
2534                     getMinimumSize();
2535                 dim = prefSize;
2536             }
2537         }
2538         return new Dimension(dim);
2539     }
2540 
2541     /**
2542      * Sets the minimum size of this component to a constant
2543      * value.  Subsequent calls to <code>getMinimumSize</code> will always
2544      * return this value.  Setting the minimum size to <code>null</code>
2545      * restores the default behavior.
2546      *
2547      * @param minimumSize the new minimum size of this component
2548      * @see #getMinimumSize
2549      * @see #isMinimumSizeSet
2550      * @since 1.5
2551      */
2552     public void setMinimumSize(Dimension minimumSize) {
2553         Dimension old;
2554         // If the minimum size was set, use it as the old value, otherwise
2555         // use null to indicate we didn't previously have a set minimum
2556         // size.
2557         if (minSizeSet) {
2558             old = this.minSize;
2559         }
2560         else {
2561             old = null;
2562         }
2563         this.minSize = minimumSize;
2564         minSizeSet = (minimumSize != null);
2565         firePropertyChange("minimumSize", old, minimumSize);
2566     }
2567 
2568     /**
2569      * Returns whether or not <code>setMinimumSize</code> has been
2570      * invoked with a non-null value.
2571      *
2572      * @return true if <code>setMinimumSize</code> has been invoked with a
2573      *              non-null value.
2574      * @since 1.5
2575      */
2576     public boolean isMinimumSizeSet() {
2577         return minSizeSet;
2578     }
2579 
2580     /**
2581      * Gets the mininimum size of this component.
2582      * @return a dimension object indicating this component's minimum size
2583      * @see #getPreferredSize
2584      * @see LayoutManager
2585      */
2586     public Dimension getMinimumSize() {
2587         return minimumSize();
2588     }
2589 
2590     /**
2591      * @deprecated As of JDK version 1.1,
2592      * replaced by <code>getMinimumSize()</code>.
2593      */
2594     @Deprecated
2595     public Dimension minimumSize() {
2596         /* Avoid grabbing the lock if a reasonable cached size value
2597          * is available.
2598          */
2599         Dimension dim = minSize;
2600         if (dim == null || !(isMinimumSizeSet() || isValid())) {
2601             synchronized (getTreeLock()) {
2602                 minSize = (peer != null) ?
2603                     peer.getMinimumSize() :
2604                     size();
2605                 dim = minSize;
2606             }
2607         }
2608         return new Dimension(dim);
2609     }
2610 
2611     /**
2612      * Sets the maximum size of this component to a constant
2613      * value.  Subsequent calls to <code>getMaximumSize</code> will always
2614      * return this value.  Setting the maximum size to <code>null</code>
2615      * restores the default behavior.
2616      *
2617      * @param maximumSize a <code>Dimension</code> containing the
2618      *          desired maximum allowable size
2619      * @see #getMaximumSize
2620      * @see #isMaximumSizeSet
2621      * @since 1.5
2622      */
2623     public void setMaximumSize(Dimension maximumSize) {
2624         // If the maximum size was set, use it as the old value, otherwise
2625         // use null to indicate we didn't previously have a set maximum
2626         // size.
2627         Dimension old;
2628         if (maxSizeSet) {
2629             old = this.maxSize;
2630         }
2631         else {
2632             old = null;
2633         }
2634         this.maxSize = maximumSize;
2635         maxSizeSet = (maximumSize != null);
2636         firePropertyChange("maximumSize", old, maximumSize);
2637     }
2638 
2639     /**
2640      * Returns true if the maximum size has been set to a non-<code>null</code>
2641      * value otherwise returns false.
2642      *
2643      * @return true if <code>maximumSize</code> is non-<code>null</code>,
2644      *          false otherwise
2645      * @since 1.5
2646      */
2647     public boolean isMaximumSizeSet() {
2648         return maxSizeSet;
2649     }
2650 
2651     /**
2652      * Gets the maximum size of this component.
2653      * @return a dimension object indicating this component's maximum size
2654      * @see #getMinimumSize
2655      * @see #getPreferredSize
2656      * @see LayoutManager
2657      */
2658     public Dimension getMaximumSize() {
2659         if (isMaximumSizeSet()) {
2660             return new Dimension(maxSize);
2661         }
2662         return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE);
2663     }
2664 
2665     /**
2666      * Returns the alignment along the x axis.  This specifies how
2667      * the component would like to be aligned relative to other
2668      * components.  The value should be a number between 0 and 1
2669      * where 0 represents alignment along the origin, 1 is aligned
2670      * the furthest away from the origin, 0.5 is centered, etc.
2671      */
2672     public float getAlignmentX() {
2673         return CENTER_ALIGNMENT;
2674     }
2675 
2676     /**
2677      * Returns the alignment along the y axis.  This specifies how
2678      * the component would like to be aligned relative to other
2679      * components.  The value should be a number between 0 and 1
2680      * where 0 represents alignment along the origin, 1 is aligned
2681      * the furthest away from the origin, 0.5 is centered, etc.
2682      */
2683     public float getAlignmentY() {
2684         return CENTER_ALIGNMENT;
2685     }
2686 
2687     /**
2688      * Returns the baseline.  The baseline is measured from the top of
2689      * the component.  This method is primarily meant for
2690      * <code>LayoutManager</code>s to align components along their
2691      * baseline.  A return value less than 0 indicates this component
2692      * does not have a reasonable baseline and that
2693      * <code>LayoutManager</code>s should not align this component on
2694      * its baseline.
2695      * <p>
2696      * The default implementation returns -1.  Subclasses that support
2697      * baseline should override appropriately.  If a value &gt;= 0 is
2698      * returned, then the component has a valid baseline for any
2699      * size &gt;= the minimum size and <code>getBaselineResizeBehavior</code>
2700      * can be used to determine how the baseline changes with size.
2701      *
2702      * @param width the width to get the baseline for
2703      * @param height the height to get the baseline for
2704      * @return the baseline or &lt; 0 indicating there is no reasonable
2705      *         baseline
2706      * @throws IllegalArgumentException if width or height is &lt; 0
2707      * @see #getBaselineResizeBehavior
2708      * @see java.awt.FontMetrics
2709      * @since 1.6
2710      */
2711     public int getBaseline(int width, int height) {
2712         if (width < 0 || height < 0) {
2713             throw new IllegalArgumentException(
2714                     "Width and height must be >= 0");
2715         }
2716         return -1;
2717     }
2718 
2719     /**
2720      * Returns an enum indicating how the baseline of the component
2721      * changes as the size changes.  This method is primarily meant for
2722      * layout managers and GUI builders.
2723      * <p>
2724      * The default implementation returns
2725      * <code>BaselineResizeBehavior.OTHER</code>.  Subclasses that have a
2726      * baseline should override appropriately.  Subclasses should
2727      * never return <code>null</code>; if the baseline can not be
2728      * calculated return <code>BaselineResizeBehavior.OTHER</code>.  Callers
2729      * should first ask for the baseline using
2730      * <code>getBaseline</code> and if a value &gt;= 0 is returned use
2731      * this method.  It is acceptable for this method to return a
2732      * value other than <code>BaselineResizeBehavior.OTHER</code> even if
2733      * <code>getBaseline</code> returns a value less than 0.
2734      *
2735      * @return an enum indicating how the baseline changes as the component
2736      *         size changes
2737      * @see #getBaseline(int, int)
2738      * @since 1.6
2739      */
2740     public BaselineResizeBehavior getBaselineResizeBehavior() {
2741         return BaselineResizeBehavior.OTHER;
2742     }
2743 
2744     /**
2745      * Prompts the layout manager to lay out this component. This is
2746      * usually called when the component (more specifically, container)
2747      * is validated.
2748      * @see #validate
2749      * @see LayoutManager
2750      */
2751     public void doLayout() {
2752         layout();
2753     }
2754 
2755     /**
2756      * @deprecated As of JDK version 1.1,
2757      * replaced by <code>doLayout()</code>.
2758      */
2759     @Deprecated
2760     public void layout() {
2761     }
2762 
2763     /**
2764      * Validates this component.
2765      * <p>
2766      * The meaning of the term <i>validating</i> is defined by the ancestors of
2767      * this class. See {@link Container#validate} for more details.
2768      *
2769      * @see       #invalidate
2770      * @see       #doLayout()
2771      * @see       LayoutManager
2772      * @see       Container#validate
2773      * @since     JDK1.0
2774      */
2775     public void validate() {
2776         synchronized (getTreeLock()) {
2777             ComponentPeer peer = this.peer;
2778             boolean wasValid = isValid();
2779             if (!wasValid && peer != null) {
2780                 Font newfont = getFont();
2781                 Font oldfont = peerFont;
2782                 if (newfont != oldfont && (oldfont == null
2783                                            || !oldfont.equals(newfont))) {
2784                     peer.setFont(newfont);
2785                     peerFont = newfont;
2786                 }
2787                 peer.layout();
2788             }
2789             valid = true;
2790             if (!wasValid) {
2791                 mixOnValidating();
2792             }
2793         }
2794     }
2795 
2796     /**
2797      * Invalidates this component and its ancestors.
2798      * <p>
2799      * All ancestors of this component up to the nearest validate root (or up
2800      * to the root of the hierarchy if there's no a validate root container
2801      * present) are marked invalid also.  Marking a container <i>invalid</i>
2802      * indicates that the container needs to be laid out.
2803      * <p>
2804      * This method is called automatically when any layout-related information
2805      * changes (e.g. setting the bounds of the component, or adding the
2806      * component to a container).
2807      * <p>
2808      * This method can be called often, so it should work fast.
2809      *
2810      * @see       #validate
2811      * @see       #doLayout
2812      * @see       LayoutManager
2813      * @see       java.awt.Container#isValidateRoot
2814      * @since     JDK1.0
2815      */
2816     public void invalidate() {
2817         synchronized (getTreeLock()) {
2818             /* Nullify cached layout and size information.
2819              * For efficiency, propagate invalidate() upwards only if
2820              * some other component hasn't already done so first.
2821              */
2822             valid = false;
2823             if (!isPreferredSizeSet()) {
2824                 prefSize = null;
2825             }
2826             if (!isMinimumSizeSet()) {
2827                 minSize = null;
2828             }
2829             if (!isMaximumSizeSet()) {
2830                 maxSize = null;
2831             }
2832             invalidateParent();
2833         }
2834     }
2835 
2836     /**
2837      * Invalidates the parent of this component if any.
2838      *
2839      * This method MUST BE invoked under the TreeLock.
2840      */
2841     void invalidateParent() {
2842         if (parent != null) {
2843             parent.invalidateIfValid();
2844         }
2845     }
2846 
2847     /** Invalidates the component unless it is already invalid.
2848      */
2849     final void invalidateIfValid() {
2850         if (isValid()) {
2851             invalidate();
2852         }
2853     }
2854 
2855     /**
2856      * Creates a graphics context for this component. This method will
2857      * return <code>null</code> if this component is currently not
2858      * displayable.
2859      * @return a graphics context for this component, or <code>null</code>
2860      *             if it has none
2861      * @see       #paint
2862      * @since     JDK1.0
2863      */
2864     public Graphics getGraphics() {
2865         if (peer instanceof LightweightPeer) {
2866             // This is for a lightweight component, need to
2867             // translate coordinate spaces and clip relative
2868             // to the parent.
2869             if (parent == null) return null;
2870             Graphics g = parent.getGraphics();
2871             if (g == null) return null;
2872             if (g instanceof ConstrainableGraphics) {
2873                 ((ConstrainableGraphics) g).constrain(x, y, width, height);
2874             } else {
2875                 g.translate(x,y);
2876                 g.setClip(0, 0, width, height);
2877             }
2878             g.setFont(getFont());
2879             return g;
2880         } else {
2881             ComponentPeer peer = this.peer;
2882             return (peer != null) ? peer.getGraphics() : null;
2883         }
2884     }
2885 
2886     final Graphics getGraphics_NoClientCode() {
2887         ComponentPeer peer = this.peer;
2888         if (peer instanceof LightweightPeer) {
2889             // This is for a lightweight component, need to
2890             // translate coordinate spaces and clip relative
2891             // to the parent.
2892             Container parent = this.parent;
2893             if (parent == null) return null;
2894             Graphics g = parent.getGraphics_NoClientCode();
2895             if (g == null) return null;
2896             if (g instanceof ConstrainableGraphics) {
2897                 ((ConstrainableGraphics) g).constrain(x, y, width, height);
2898             } else {
2899                 g.translate(x,y);
2900                 g.setClip(0, 0, width, height);
2901             }
2902             g.setFont(getFont_NoClientCode());
2903             return g;
2904         } else {
2905             return (peer != null) ? peer.getGraphics() : null;
2906         }
2907     }
2908 
2909     /**
2910      * Gets the font metrics for the specified font.
2911      * Warning: Since Font metrics are affected by the
2912      * {@link java.awt.font.FontRenderContext FontRenderContext} and
2913      * this method does not provide one, it can return only metrics for
2914      * the default render context which may not match that used when
2915      * rendering on the Component if {@link Graphics2D} functionality is being
2916      * used. Instead metrics can be obtained at rendering time by calling
2917      * {@link Graphics#getFontMetrics()} or text measurement APIs on the
2918      * {@link Font Font} class.
2919      * @param font the font for which font metrics is to be
2920      *          obtained
2921      * @return the font metrics for <code>font</code>
2922      * @see       #getFont
2923      * @see       #getPeer
2924      * @see       java.awt.peer.ComponentPeer#getFontMetrics(Font)
2925      * @see       Toolkit#getFontMetrics(Font)
2926      * @since     JDK1.0
2927      */
2928     public FontMetrics getFontMetrics(Font font) {
2929         // REMIND: PlatformFont flag should be obsolete soon...
2930         if (sun.font.FontManager.usePlatformFontMetrics()) {
2931             if (peer != null &&
2932                 !(peer instanceof LightweightPeer)) {
2933                 return peer.getFontMetrics(font);
2934             }
2935         }
2936         return sun.font.FontDesignMetrics.getMetrics(font);
2937     }
2938 
2939     /**
2940      * Sets the cursor image to the specified cursor.  This cursor
2941      * image is displayed when the <code>contains</code> method for
2942      * this component returns true for the current cursor location, and
2943      * this Component is visible, displayable, and enabled. Setting the
2944      * cursor of a <code>Container</code> causes that cursor to be displayed
2945      * within all of the container's subcomponents, except for those
2946      * that have a non-<code>null</code> cursor.
2947      * <p>
2948      * The method may have no visual effect if the Java platform
2949      * implementation and/or the native system do not support
2950      * changing the mouse cursor shape.
2951      * @param cursor One of the constants defined
2952      *          by the <code>Cursor</code> class;
2953      *          if this parameter is <code>null</code>
2954      *          then this component will inherit
2955      *          the cursor of its parent
2956      * @see       #isEnabled
2957      * @see       #isShowing
2958      * @see       #getCursor
2959      * @see       #contains
2960      * @see       Toolkit#createCustomCursor
2961      * @see       Cursor
2962      * @since     JDK1.1
2963      */
2964     public void setCursor(Cursor cursor) {
2965         this.cursor = cursor;
2966         updateCursorImmediately();
2967     }
2968 
2969     /**
2970      * Updates the cursor.  May not be invoked from the native
2971      * message pump.
2972      */
2973     final void updateCursorImmediately() {
2974         if (peer instanceof LightweightPeer) {
2975             Container nativeContainer = getNativeContainer();
2976 
2977             if (nativeContainer == null) return;
2978 
2979             ComponentPeer cPeer = nativeContainer.getPeer();
2980 
2981             if (cPeer != null) {
2982                 cPeer.updateCursorImmediately();
2983             }
2984         } else if (peer != null) {
2985             peer.updateCursorImmediately();
2986         }
2987     }
2988 
2989     /**
2990      * Gets the cursor set in the component. If the component does
2991      * not have a cursor set, the cursor of its parent is returned.
2992      * If no cursor is set in the entire hierarchy,
2993      * <code>Cursor.DEFAULT_CURSOR</code> is returned.
2994      * @see #setCursor
2995      * @since      JDK1.1
2996      */
2997     public Cursor getCursor() {
2998         return getCursor_NoClientCode();
2999     }
3000 
3001     final Cursor getCursor_NoClientCode() {
3002         Cursor cursor = this.cursor;
3003         if (cursor != null) {
3004             return cursor;
3005         }
3006         Container parent = this.parent;
3007         if (parent != null) {
3008             return parent.getCursor_NoClientCode();
3009         } else {
3010             return Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
3011         }
3012     }
3013 
3014     /**
3015      * Returns whether the cursor has been explicitly set for this Component.
3016      * If this method returns <code>false</code>, this Component is inheriting
3017      * its cursor from an ancestor.
3018      *
3019      * @return <code>true</code> if the cursor has been explicitly set for this
3020      *         Component; <code>false</code> otherwise.
3021      * @since 1.4
3022      */
3023     public boolean isCursorSet() {
3024         return (cursor != null);
3025     }
3026 
3027     /**
3028      * Paints this component.
3029      * <p>
3030      * This method is called when the contents of the component should
3031      * be painted; such as when the component is first being shown or
3032      * is damaged and in need of repair.  The clip rectangle in the
3033      * <code>Graphics</code> parameter is set to the area
3034      * which needs to be painted.
3035      * Subclasses of <code>Component</code> that override this
3036      * method need not call <code>super.paint(g)</code>.
3037      * <p>
3038      * For performance reasons, <code>Component</code>s with zero width
3039      * or height aren't considered to need painting when they are first shown,
3040      * and also aren't considered to need repair.
3041      * <p>
3042      * <b>Note</b>: For more information on the paint mechanisms utilitized
3043      * by AWT and Swing, including information on how to write the most
3044      * efficient painting code, see
3045      * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>.
3046      *
3047      * @param g the graphics context to use for painting
3048      * @see       #update
3049      * @since     JDK1.0
3050      */
3051     public void paint(Graphics g) {
3052     }
3053 
3054     /**
3055      * Updates this component.
3056      * <p>
3057      * If this component is not a lightweight component, the
3058      * AWT calls the <code>update</code> method in response to
3059      * a call to <code>repaint</code>.  You can assume that
3060      * the background is not cleared.
3061      * <p>
3062      * The <code>update</code> method of <code>Component</code>
3063      * calls this component's <code>paint</code> method to redraw
3064      * this component.  This method is commonly overridden by subclasses
3065      * which need to do additional work in response to a call to
3066      * <code>repaint</code>.
3067      * Subclasses of Component that override this method should either
3068      * call <code>super.update(g)</code>, or call <code>paint(g)</code>
3069      * directly from their <code>update</code> method.
3070      * <p>
3071      * The origin of the graphics context, its
3072      * (<code>0</code>,&nbsp;<code>0</code>) coordinate point, is the
3073      * top-left corner of this component. The clipping region of the
3074      * graphics context is the bounding rectangle of this component.
3075      *
3076      * <p>
3077      * <b>Note</b>: For more information on the paint mechanisms utilitized
3078      * by AWT and Swing, including information on how to write the most
3079      * efficient painting code, see
3080      * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>.
3081      *
3082      * @param g the specified context to use for updating
3083      * @see       #paint
3084      * @see       #repaint()
3085      * @since     JDK1.0
3086      */
3087     public void update(Graphics g) {
3088         paint(g);
3089     }
3090 
3091     /**
3092      * Paints this component and all of its subcomponents.
3093      * <p>
3094      * The origin of the graphics context, its
3095      * (<code>0</code>,&nbsp;<code>0</code>) coordinate point, is the
3096      * top-left corner of this component. The clipping region of the
3097      * graphics context is the bounding rectangle of this component.
3098      *
3099      * @param     g   the graphics context to use for painting
3100      * @see       #paint
3101      * @since     JDK1.0
3102      */
3103     public void paintAll(Graphics g) {
3104         if (isShowing()) {
3105             GraphicsCallback.PeerPaintCallback.getInstance().
3106                 runOneComponent(this, new Rectangle(0, 0, width, height),
3107                                 g, g.getClip(),
3108                                 GraphicsCallback.LIGHTWEIGHTS |
3109                                 GraphicsCallback.HEAVYWEIGHTS);
3110         }
3111     }
3112 
3113     /**
3114      * Simulates the peer callbacks into java.awt for painting of
3115      * lightweight Components.
3116      * @param     g   the graphics context to use for painting
3117      * @see       #paintAll
3118      */
3119     void lightweightPaint(Graphics g) {
3120         paint(g);
3121     }
3122 
3123     /**
3124      * Paints all the heavyweight subcomponents.
3125      */
3126     void paintHeavyweightComponents(Graphics g) {
3127     }
3128 
3129     /**
3130      * Repaints this component.
3131      * <p>
3132      * If this component is a lightweight component, this method
3133      * causes a call to this component's <code>paint</code>
3134      * method as soon as possible.  Otherwise, this method causes
3135      * a call to this component's <code>update</code> method as soon
3136      * as possible.
3137      * <p>
3138      * <b>Note</b>: For more information on the paint mechanisms utilitized
3139      * by AWT and Swing, including information on how to write the most
3140      * efficient painting code, see
3141      * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>.
3142 
3143      *
3144      * @see       #update(Graphics)
3145      * @since     JDK1.0
3146      */
3147     public void repaint() {
3148         repaint(0, 0, 0, width, height);
3149     }
3150 
3151     /**
3152      * Repaints the component.  If this component is a lightweight
3153      * component, this results in a call to <code>paint</code>
3154      * within <code>tm</code> milliseconds.
3155      * <p>
3156      * <b>Note</b>: For more information on the paint mechanisms utilitized
3157      * by AWT and Swing, including information on how to write the most
3158      * efficient painting code, see
3159      * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>.
3160      *
3161      * @param tm maximum time in milliseconds before update
3162      * @see #paint
3163      * @see #update(Graphics)
3164      * @since JDK1.0
3165      */
3166     public void repaint(long tm) {
3167         repaint(tm, 0, 0, width, height);
3168     }
3169 
3170     /**
3171      * Repaints the specified rectangle of this component.
3172      * <p>
3173      * If this component is a lightweight component, this method
3174      * causes a call to this component's <code>paint</code> method
3175      * as soon as possible.  Otherwise, this method causes a call to
3176      * this component's <code>update</code> method as soon as possible.
3177      * <p>
3178      * <b>Note</b>: For more information on the paint mechanisms utilitized
3179      * by AWT and Swing, including information on how to write the most
3180      * efficient painting code, see
3181      * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>.
3182      *
3183      * @param     x   the <i>x</i> coordinate
3184      * @param     y   the <i>y</i> coordinate
3185      * @param     width   the width
3186      * @param     height  the height
3187      * @see       #update(Graphics)
3188      * @since     JDK1.0
3189      */
3190     public void repaint(int x, int y, int width, int height) {
3191         repaint(0, x, y, width, height);
3192     }
3193 
3194     /**
3195      * Repaints the specified rectangle of this component within
3196      * <code>tm</code> milliseconds.
3197      * <p>
3198      * If this component is a lightweight component, this method causes
3199      * a call to this component's <code>paint</code> method.
3200      * Otherwise, this method causes a call to this component's
3201      * <code>update</code> method.
3202      * <p>
3203      * <b>Note</b>: For more information on the paint mechanisms utilitized
3204      * by AWT and Swing, including information on how to write the most
3205      * efficient painting code, see
3206      * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>.
3207      *
3208      * @param     tm   maximum time in milliseconds before update
3209      * @param     x    the <i>x</i> coordinate
3210      * @param     y    the <i>y</i> coordinate
3211      * @param     width    the width
3212      * @param     height   the height
3213      * @see       #update(Graphics)
3214      * @since     JDK1.0
3215      */
3216     public void repaint(long tm, int x, int y, int width, int height) {
3217         if (this.peer instanceof LightweightPeer) {
3218             // Needs to be translated to parent coordinates since
3219             // a parent native container provides the actual repaint
3220             // services.  Additionally, the request is restricted to
3221             // the bounds of the component.
3222             if (parent != null) {
3223                 if (x < 0) {
3224                     width += x;
3225                     x = 0;
3226                 }
3227                 if (y < 0) {
3228                     height += y;
3229                     y = 0;
3230                 }
3231 
3232                 int pwidth = (width > this.width) ? this.width : width;
3233                 int pheight = (height > this.height) ? this.height : height;
3234 
3235                 if (pwidth <= 0 || pheight <= 0) {
3236                     return;
3237                 }
3238 
3239                 int px = this.x + x;
3240                 int py = this.y + y;
3241                 parent.repaint(tm, px, py, pwidth, pheight);
3242             }
3243         } else {
3244             if (isVisible() && (this.peer != null) &&
3245                 (width > 0) && (height > 0)) {
3246                 PaintEvent e = new PaintEvent(this, PaintEvent.UPDATE,
3247                                               new Rectangle(x, y, width, height));
3248                 Toolkit.getEventQueue().postEvent(e);
3249             }
3250         }
3251     }
3252 
3253     /**
3254      * Prints this component. Applications should override this method
3255      * for components that must do special processing before being
3256      * printed or should be printed differently than they are painted.
3257      * <p>
3258      * The default implementation of this method calls the
3259      * <code>paint</code> method.
3260      * <p>
3261      * The origin of the graphics context, its
3262      * (<code>0</code>,&nbsp;<code>0</code>) coordinate point, is the
3263      * top-left corner of this component. The clipping region of the
3264      * graphics context is the bounding rectangle of this component.
3265      * @param     g   the graphics context to use for printing
3266      * @see       #paint(Graphics)
3267      * @since     JDK1.0
3268      */
3269     public void print(Graphics g) {
3270         paint(g);
3271     }
3272 
3273     /**
3274      * Prints this component and all of its subcomponents.
3275      * <p>
3276      * The origin of the graphics context, its
3277      * (<code>0</code>,&nbsp;<code>0</code>) coordinate point, is the
3278      * top-left corner of this component. The clipping region of the
3279      * graphics context is the bounding rectangle of this component.
3280      * @param     g   the graphics context to use for printing
3281      * @see       #print(Graphics)
3282      * @since     JDK1.0
3283      */
3284     public void printAll(Graphics g) {
3285         if (isShowing()) {
3286             GraphicsCallback.PeerPrintCallback.getInstance().
3287                 runOneComponent(this, new Rectangle(0, 0, width, height),
3288                                 g, g.getClip(),
3289                                 GraphicsCallback.LIGHTWEIGHTS |
3290                                 GraphicsCallback.HEAVYWEIGHTS);
3291         }
3292     }
3293 
3294     /**
3295      * Simulates the peer callbacks into java.awt for printing of
3296      * lightweight Components.
3297      * @param     g   the graphics context to use for printing
3298      * @see       #printAll
3299      */
3300     void lightweightPrint(Graphics g) {
3301         print(g);
3302     }
3303 
3304     /**
3305      * Prints all the heavyweight subcomponents.
3306      */
3307     void printHeavyweightComponents(Graphics g) {
3308     }
3309 
3310     private Insets getInsets_NoClientCode() {
3311         ComponentPeer peer = this.peer;
3312         if (peer instanceof ContainerPeer) {
3313             return (Insets)((ContainerPeer)peer).getInsets().clone();
3314         }
3315         return new Insets(0, 0, 0, 0);
3316     }
3317 
3318     /**
3319      * Repaints the component when the image has changed.
3320      * This <code>imageUpdate</code> method of an <code>ImageObserver</code>
3321      * is called when more information about an
3322      * image which had been previously requested using an asynchronous
3323      * routine such as the <code>drawImage</code> method of
3324      * <code>Graphics</code> becomes available.
3325      * See the definition of <code>imageUpdate</code> for
3326      * more information on this method and its arguments.
3327      * <p>
3328      * The <code>imageUpdate</code> method of <code>Component</code>
3329      * incrementally draws an image on the component as more of the bits
3330      * of the image are available.
3331      * <p>
3332      * If the system property <code>awt.image.incrementaldraw</code>
3333      * is missing or has the value <code>true</code>, the image is
3334      * incrementally drawn. If the system property has any other value,
3335      * then the image is not drawn until it has been completely loaded.
3336      * <p>
3337      * Also, if incremental drawing is in effect, the value of the
3338      * system property <code>awt.image.redrawrate</code> is interpreted
3339      * as an integer to give the maximum redraw rate, in milliseconds. If
3340      * the system property is missing or cannot be interpreted as an
3341      * integer, the redraw rate is once every 100ms.
3342      * <p>
3343      * The interpretation of the <code>x</code>, <code>y</code>,
3344      * <code>width</code>, and <code>height</code> arguments depends on
3345      * the value of the <code>infoflags</code> argument.
3346      *
3347      * @param     img   the image being observed
3348      * @param     infoflags   see <code>imageUpdate</code> for more information
3349      * @param     x   the <i>x</i> coordinate
3350      * @param     y   the <i>y</i> coordinate
3351      * @param     w   the width
3352      * @param     h   the height
3353      * @return    <code>false</code> if the infoflags indicate that the
3354      *            image is completely loaded; <code>true</code> otherwise.
3355      *
3356      * @see     java.awt.image.ImageObserver
3357      * @see     Graphics#drawImage(Image, int, int, Color, java.awt.image.ImageObserver)
3358      * @see     Graphics#drawImage(Image, int, int, java.awt.image.ImageObserver)
3359      * @see     Graphics#drawImage(Image, int, int, int, int, Color, java.awt.image.ImageObserver)
3360      * @see     Graphics#drawImage(Image, int, int, int, int, java.awt.image.ImageObserver)
3361      * @see     java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
3362      * @since   JDK1.0
3363      */
3364     public boolean imageUpdate(Image img, int infoflags,
3365                                int x, int y, int w, int h) {
3366         int rate = -1;
3367         if ((infoflags & (FRAMEBITS|ALLBITS)) != 0) {
3368             rate = 0;
3369         } else if ((infoflags & SOMEBITS) != 0) {
3370             if (isInc) {
3371                 rate = incRate;
3372                 if (rate < 0) {
3373                     rate = 0;
3374                 }
3375             }
3376         }
3377         if (rate >= 0) {
3378             repaint(rate, 0, 0, width, height);
3379         }
3380         return (infoflags & (ALLBITS|ABORT)) == 0;
3381     }
3382 
3383     /**
3384      * Creates an image from the specified image producer.
3385      * @param     producer  the image producer
3386      * @return    the image produced
3387      * @since     JDK1.0
3388      */
3389     public Image createImage(ImageProducer producer) {
3390         ComponentPeer peer = this.peer;
3391         if ((peer != null) && ! (peer instanceof LightweightPeer)) {
3392             return peer.createImage(producer);
3393         }
3394         return getToolkit().createImage(producer);
3395     }
3396 
3397     /**
3398      * Creates an off-screen drawable image
3399      *     to be used for double buffering.
3400      * @param     width the specified width
3401      * @param     height the specified height
3402      * @return    an off-screen drawable image, which can be used for double
3403      *    buffering.  The return value may be <code>null</code> if the
3404      *    component is not displayable.  This will always happen if
3405      *    <code>GraphicsEnvironment.isHeadless()</code> returns
3406      *    <code>true</code>.
3407      * @see #isDisplayable
3408      * @see GraphicsEnvironment#isHeadless
3409      * @since     JDK1.0
3410      */
3411     public Image createImage(int width, int height) {
3412         ComponentPeer peer = this.peer;
3413         if (peer instanceof LightweightPeer) {
3414             if (parent != null) { return parent.createImage(width, height); }
3415             else { return null;}
3416         } else {
3417             return (peer != null) ? peer.createImage(width, height) : null;
3418         }
3419     }
3420 
3421     /**
3422      * Creates a volatile off-screen drawable image
3423      *     to be used for double buffering.
3424      * @param     width the specified width.
3425      * @param     height the specified height.
3426      * @return    an off-screen drawable image, which can be used for double
3427      *    buffering.  The return value may be <code>null</code> if the
3428      *    component is not displayable.  This will always happen if
3429      *    <code>GraphicsEnvironment.isHeadless()</code> returns
3430      *    <code>true</code>.
3431      * @see java.awt.image.VolatileImage
3432      * @see #isDisplayable
3433      * @see GraphicsEnvironment#isHeadless
3434      * @since     1.4
3435      */
3436     public VolatileImage createVolatileImage(int width, int height) {
3437         ComponentPeer peer = this.peer;
3438         if (peer instanceof LightweightPeer) {
3439             if (parent != null) {
3440                 return parent.createVolatileImage(width, height);
3441             }
3442             else { return null;}
3443         } else {
3444             return (peer != null) ?
3445                 peer.createVolatileImage(width, height) : null;
3446         }
3447     }
3448 
3449     /**
3450      * Creates a volatile off-screen drawable image, with the given capabilities.
3451      * The contents of this image may be lost at any time due
3452      * to operating system issues, so the image must be managed
3453      * via the <code>VolatileImage</code> interface.
3454      * @param width the specified width.
3455      * @param height the specified height.
3456      * @param caps the image capabilities
3457      * @exception AWTException if an image with the specified capabilities cannot
3458      * be created
3459      * @return a VolatileImage object, which can be used
3460      * to manage surface contents loss and capabilities.
3461      * @see java.awt.image.VolatileImage
3462      * @since 1.4
3463      */
3464     public VolatileImage createVolatileImage(int width, int height,
3465                                              ImageCapabilities caps) throws AWTException {
3466         // REMIND : check caps
3467         return createVolatileImage(width, height);
3468     }
3469 
3470     /**
3471      * Prepares an image for rendering on this component.  The image
3472      * data is downloaded asynchronously in another thread and the
3473      * appropriate screen representation of the image is generated.
3474      * @param     image   the <code>Image</code> for which to
3475      *                    prepare a screen representation
3476      * @param     observer   the <code>ImageObserver</code> object
3477      *                       to be notified as the image is being prepared
3478      * @return    <code>true</code> if the image has already been fully
3479      *           prepared; <code>false</code> otherwise
3480      * @since     JDK1.0
3481      */
3482     public boolean prepareImage(Image image, ImageObserver observer) {
3483         return prepareImage(image, -1, -1, observer);
3484     }
3485 
3486     /**
3487      * Prepares an image for rendering on this component at the
3488      * specified width and height.
3489      * <p>
3490      * The image data is downloaded asynchronously in another thread,
3491      * and an appropriately scaled screen representation of the image is
3492      * generated.
3493      * @param     image    the instance of <code>Image</code>
3494      *            for which to prepare a screen representation
3495      * @param     width    the width of the desired screen representation
3496      * @param     height   the height of the desired screen representation
3497      * @param     observer   the <code>ImageObserver</code> object
3498      *            to be notified as the image is being prepared
3499      * @return    <code>true</code> if the image has already been fully
3500      *          prepared; <code>false</code> otherwise
3501      * @see       java.awt.image.ImageObserver
3502      * @since     JDK1.0
3503      */
3504     public boolean prepareImage(Image image, int width, int height,
3505                                 ImageObserver observer) {
3506         ComponentPeer peer = this.peer;
3507         if (peer instanceof LightweightPeer) {
3508             return (parent != null)
3509                 ? parent.prepareImage(image, width, height, observer)
3510                 : getToolkit().prepareImage(image, width, height, observer);
3511         } else {
3512             return (peer != null)
3513                 ? peer.prepareImage(image, width, height, observer)
3514                 : getToolkit().prepareImage(image, width, height, observer);
3515         }
3516     }
3517 
3518     /**
3519      * Returns the status of the construction of a screen representation
3520      * of the specified image.
3521      * <p>
3522      * This method does not cause the image to begin loading. An
3523      * application must use the <code>prepareImage</code> method
3524      * to force the loading of an image.
3525      * <p>
3526      * Information on the flags returned by this method can be found
3527      * with the discussion of the <code>ImageObserver</code> interface.
3528      * @param     image   the <code>Image</code> object whose status
3529      *            is being checked
3530      * @param     observer   the <code>ImageObserver</code>
3531      *            object to be notified as the image is being prepared
3532      * @return  the bitwise inclusive <b>OR</b> of
3533      *            <code>ImageObserver</code> flags indicating what
3534      *            information about the image is currently available
3535      * @see      #prepareImage(Image, int, int, java.awt.image.ImageObserver)
3536      * @see      Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver)
3537      * @see      java.awt.image.ImageObserver
3538      * @since    JDK1.0
3539      */
3540     public int checkImage(Image image, ImageObserver observer) {
3541         return checkImage(image, -1, -1, observer);
3542     }
3543 
3544     /**
3545      * Returns the status of the construction of a screen representation
3546      * of the specified image.
3547      * <p>
3548      * This method does not cause the image to begin loading. An
3549      * application must use the <code>prepareImage</code> method
3550      * to force the loading of an image.
3551      * <p>
3552      * The <code>checkImage</code> method of <code>Component</code>
3553      * calls its peer's <code>checkImage</code> method to calculate
3554      * the flags. If this component does not yet have a peer, the
3555      * component's toolkit's <code>checkImage</code> method is called
3556      * instead.
3557      * <p>
3558      * Information on the flags returned by this method can be found
3559      * with the discussion of the <code>ImageObserver</code> interface.
3560      * @param     image   the <code>Image</code> object whose status
3561      *                    is being checked
3562      * @param     width   the width of the scaled version
3563      *                    whose status is to be checked
3564      * @param     height  the height of the scaled version
3565      *                    whose status is to be checked
3566      * @param     observer   the <code>ImageObserver</code> object
3567      *                    to be notified as the image is being prepared
3568      * @return    the bitwise inclusive <b>OR</b> of
3569      *            <code>ImageObserver</code> flags indicating what
3570      *            information about the image is currently available
3571      * @see      #prepareImage(Image, int, int, java.awt.image.ImageObserver)
3572      * @see      Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver)
3573      * @see      java.awt.image.ImageObserver
3574      * @since    JDK1.0
3575      */
3576     public int checkImage(Image image, int width, int height,
3577                           ImageObserver observer) {
3578         ComponentPeer peer = this.peer;
3579         if (peer instanceof LightweightPeer) {
3580             return (parent != null)
3581                 ? parent.checkImage(image, width, height, observer)
3582                 : getToolkit().checkImage(image, width, height, observer);
3583         } else {
3584             return (peer != null)
3585                 ? peer.checkImage(image, width, height, observer)
3586                 : getToolkit().checkImage(image, width, height, observer);
3587         }
3588     }
3589 
3590     /**
3591      * Creates a new strategy for multi-buffering on this component.
3592      * Multi-buffering is useful for rendering performance.  This method
3593      * attempts to create the best strategy available with the number of
3594      * buffers supplied.  It will always create a <code>BufferStrategy</code>
3595      * with that number of buffers.
3596      * A page-flipping strategy is attempted first, then a blitting strategy
3597      * using accelerated buffers.  Finally, an unaccelerated blitting
3598      * strategy is used.
3599      * <p>
3600      * Each time this method is called,
3601      * the existing buffer strategy for this component is discarded.
3602      * @param numBuffers number of buffers to create, including the front buffer
3603      * @exception IllegalArgumentException if numBuffers is less than 1.
3604      * @exception IllegalStateException if the component is not displayable
3605      * @see #isDisplayable
3606      * @see Window#getBufferStrategy()
3607      * @see Canvas#getBufferStrategy()
3608      * @since 1.4
3609      */
3610     void createBufferStrategy(int numBuffers) {
3611         BufferCapabilities bufferCaps;
3612         if (numBuffers > 1) {
3613             // Try to create a page-flipping strategy
3614             bufferCaps = new BufferCapabilities(new ImageCapabilities(true),
3615                                                 new ImageCapabilities(true),
3616                                                 BufferCapabilities.FlipContents.UNDEFINED);
3617             try {
3618                 createBufferStrategy(numBuffers, bufferCaps);
3619                 return; // Success
3620             } catch (AWTException e) {
3621                 // Failed
3622             }
3623         }
3624         // Try a blitting (but still accelerated) strategy
3625         bufferCaps = new BufferCapabilities(new ImageCapabilities(true),
3626                                             new ImageCapabilities(true),
3627                                             null);
3628         try {
3629             createBufferStrategy(numBuffers, bufferCaps);
3630             return; // Success
3631         } catch (AWTException e) {
3632             // Failed
3633         }
3634         // Try an unaccelerated blitting strategy
3635         bufferCaps = new BufferCapabilities(new ImageCapabilities(false),
3636                                             new ImageCapabilities(false),
3637                                             null);
3638         try {
3639             createBufferStrategy(numBuffers, bufferCaps);
3640             return; // Success
3641         } catch (AWTException e) {
3642             // Failed
3643         }
3644         // Code should never reach here (an unaccelerated blitting
3645         // strategy should always work)
3646         throw new InternalError("Could not create a buffer strategy");
3647     }
3648 
3649     /**
3650      * Creates a new strategy for multi-buffering on this component with the
3651      * required buffer capabilities.  This is useful, for example, if only
3652      * accelerated memory or page flipping is desired (as specified by the
3653      * buffer capabilities).
3654      * <p>
3655      * Each time this method
3656      * is called, <code>dispose</code> will be invoked on the existing
3657      * <code>BufferStrategy</code>.
3658      * @param numBuffers number of buffers to create
3659      * @param caps the required capabilities for creating the buffer strategy;
3660      * cannot be <code>null</code>
3661      * @exception AWTException if the capabilities supplied could not be
3662      * supported or met; this may happen, for example, if there is not enough
3663      * accelerated memory currently available, or if page flipping is specified
3664      * but not possible.
3665      * @exception IllegalArgumentException if numBuffers is less than 1, or if
3666      * caps is <code>null</code>
3667      * @see Window#getBufferStrategy()
3668      * @see Canvas#getBufferStrategy()
3669      * @since 1.4
3670      */
3671     void createBufferStrategy(int numBuffers,
3672                               BufferCapabilities caps) throws AWTException {
3673         // Check arguments
3674         if (numBuffers < 1) {
3675             throw new IllegalArgumentException(
3676                 "Number of buffers must be at least 1");
3677         }
3678         if (caps == null) {
3679             throw new IllegalArgumentException("No capabilities specified");
3680         }
3681         // Destroy old buffers
3682         if (bufferStrategy != null) {
3683             bufferStrategy.dispose();
3684         }
3685         if (numBuffers == 1) {
3686             bufferStrategy = new SingleBufferStrategy(caps);
3687         } else {
3688             SunGraphicsEnvironment sge = (SunGraphicsEnvironment)
3689                 GraphicsEnvironment.getLocalGraphicsEnvironment();
3690             if (!caps.isPageFlipping() && sge.isFlipStrategyPreferred(peer)) {
3691                 caps = new ProxyCapabilities(caps);
3692             }
3693             // assert numBuffers > 1;
3694             if (caps.isPageFlipping()) {
3695                 bufferStrategy = new FlipSubRegionBufferStrategy(numBuffers, caps);
3696             } else {
3697                 bufferStrategy = new BltSubRegionBufferStrategy(numBuffers, caps);
3698             }
3699         }
3700     }
3701 
3702     /**
3703      * This is a proxy capabilities class used when a FlipBufferStrategy
3704      * is created instead of the requested Blit strategy.
3705      *
3706      * @see sun.awt.SunGraphicsEnvironment#isFlipStrategyPreferred(ComponentPeer)
3707      */
3708     private class ProxyCapabilities extends ExtendedBufferCapabilities {
3709         private BufferCapabilities orig;
3710         private ProxyCapabilities(BufferCapabilities orig) {
3711             super(orig.getFrontBufferCapabilities(),
3712                   orig.getBackBufferCapabilities(),
3713                   orig.getFlipContents() ==
3714                       BufferCapabilities.FlipContents.BACKGROUND ?
3715                       BufferCapabilities.FlipContents.BACKGROUND :
3716                       BufferCapabilities.FlipContents.COPIED);
3717             this.orig = orig;
3718         }
3719     }
3720 
3721     /**
3722      * @return the buffer strategy used by this component
3723      * @see Window#createBufferStrategy
3724      * @see Canvas#createBufferStrategy
3725      * @since 1.4
3726      */
3727     BufferStrategy getBufferStrategy() {
3728         return bufferStrategy;
3729     }
3730 
3731     /**
3732      * @return the back buffer currently used by this component's
3733      * BufferStrategy.  If there is no BufferStrategy or no
3734      * back buffer, this method returns null.
3735      */
3736     Image getBackBuffer() {
3737         if (bufferStrategy != null) {
3738             if (bufferStrategy instanceof BltBufferStrategy) {
3739                 BltBufferStrategy bltBS = (BltBufferStrategy)bufferStrategy;
3740                 return bltBS.getBackBuffer();
3741             } else if (bufferStrategy instanceof FlipBufferStrategy) {
3742                 FlipBufferStrategy flipBS = (FlipBufferStrategy)bufferStrategy;
3743                 return flipBS.getBackBuffer();
3744             }
3745         }
3746         return null;
3747     }
3748 
3749     /**
3750      * Inner class for flipping buffers on a component.  That component must
3751      * be a <code>Canvas</code> or <code>Window</code>.
3752      * @see Canvas
3753      * @see Window
3754      * @see java.awt.image.BufferStrategy
3755      * @author Michael Martak
3756      * @since 1.4
3757      */
3758     protected class FlipBufferStrategy extends BufferStrategy {
3759         /**
3760          * The number of buffers
3761          */
3762         protected int numBuffers; // = 0
3763         /**
3764          * The buffering capabilities
3765          */
3766         protected BufferCapabilities caps; // = null
3767         /**
3768          * The drawing buffer
3769          */
3770         protected Image drawBuffer; // = null
3771         /**
3772          * The drawing buffer as a volatile image
3773          */
3774         protected VolatileImage drawVBuffer; // = null
3775         /**
3776          * Whether or not the drawing buffer has been recently restored from
3777          * a lost state.
3778          */
3779         protected boolean validatedContents; // = false
3780         /**
3781          * Size of the back buffers.  (Note: these fields were added in 6.0
3782          * but kept package-private to avoid exposing them in the spec.
3783          * None of these fields/methods really should have been marked
3784          * protected when they were introduced in 1.4, but now we just have
3785          * to live with that decision.)
3786          */
3787         int width;
3788         int height;
3789 
3790         /**
3791          * Creates a new flipping buffer strategy for this component.
3792          * The component must be a <code>Canvas</code> or <code>Window</code>.
3793          * @see Canvas
3794          * @see Window
3795          * @param numBuffers the number of buffers
3796          * @param caps the capabilities of the buffers
3797          * @exception AWTException if the capabilities supplied could not be
3798          * supported or met
3799          * @exception ClassCastException if the component is not a canvas or
3800          * window.
3801          */
3802         protected FlipBufferStrategy(int numBuffers, BufferCapabilities caps)
3803             throws AWTException
3804         {
3805             if (!(Component.this instanceof Window) &&
3806                 !(Component.this instanceof Canvas))
3807             {
3808                 throw new ClassCastException(
3809                     "Component must be a Canvas or Window");
3810             }
3811             this.numBuffers = numBuffers;
3812             this.caps = caps;
3813             createBuffers(numBuffers, caps);
3814         }
3815 
3816         /**
3817          * Creates one or more complex, flipping buffers with the given
3818          * capabilities.
3819          * @param numBuffers number of buffers to create; must be greater than
3820          * one
3821          * @param caps the capabilities of the buffers.
3822          * <code>BufferCapabilities.isPageFlipping</code> must be
3823          * <code>true</code>.
3824          * @exception AWTException if the capabilities supplied could not be
3825          * supported or met
3826          * @exception IllegalStateException if the component has no peer
3827          * @exception IllegalArgumentException if numBuffers is less than two,
3828          * or if <code>BufferCapabilities.isPageFlipping</code> is not
3829          * <code>true</code>.
3830          * @see java.awt.BufferCapabilities#isPageFlipping()
3831          */
3832         protected void createBuffers(int numBuffers, BufferCapabilities caps)
3833             throws AWTException
3834         {
3835             if (numBuffers < 2) {
3836                 throw new IllegalArgumentException(
3837                     "Number of buffers cannot be less than two");
3838             } else if (peer == null) {
3839                 throw new IllegalStateException(
3840                     "Component must have a valid peer");
3841             } else if (caps == null || !caps.isPageFlipping()) {
3842                 throw new IllegalArgumentException(
3843                     "Page flipping capabilities must be specified");
3844             }
3845 
3846             // save the current bounds
3847             width = getWidth();
3848             height = getHeight();
3849 
3850             if (drawBuffer != null) {
3851                 // dispose the existing backbuffers
3852                 drawBuffer = null;
3853                 drawVBuffer = null;
3854                 destroyBuffers();
3855                 // ... then recreate the backbuffers
3856             }
3857 
3858             if (caps instanceof ExtendedBufferCapabilities) {
3859                 ExtendedBufferCapabilities ebc =
3860                     (ExtendedBufferCapabilities)caps;
3861                 if (ebc.getVSync() == VSYNC_ON) {
3862                     // if this buffer strategy is not allowed to be v-synced,
3863                     // change the caps that we pass to the peer but keep on
3864                     // trying to create v-synced buffers;
3865                     // do not throw IAE here in case it is disallowed, see
3866                     // ExtendedBufferCapabilities for more info
3867                     if (!VSyncedBSManager.vsyncAllowed(this)) {
3868                         caps = ebc.derive(VSYNC_DEFAULT);
3869                     }
3870                 }
3871             }
3872 
3873             peer.createBuffers(numBuffers, caps);
3874             updateInternalBuffers();
3875         }
3876 
3877         /**
3878          * Updates internal buffers (both volatile and non-volatile)
3879          * by requesting the back-buffer from the peer.
3880          */
3881         private void updateInternalBuffers() {
3882             // get the images associated with the draw buffer
3883             drawBuffer = getBackBuffer();
3884             if (drawBuffer instanceof VolatileImage) {
3885                 drawVBuffer = (VolatileImage)drawBuffer;
3886             } else {
3887                 drawVBuffer = null;
3888             }
3889         }
3890 
3891         /**
3892          * @return direct access to the back buffer, as an image.
3893          * @exception IllegalStateException if the buffers have not yet
3894          * been created
3895          */
3896         protected Image getBackBuffer() {
3897             if (peer != null) {
3898                 return peer.getBackBuffer();
3899             } else {
3900                 throw new IllegalStateException(
3901                     "Component must have a valid peer");
3902             }
3903         }
3904 
3905         /**
3906          * Flipping moves the contents of the back buffer to the front buffer,
3907          * either by copying or by moving the video pointer.
3908          * @param flipAction an integer value describing the flipping action
3909          * for the contents of the back buffer.  This should be one of the
3910          * values of the <code>BufferCapabilities.FlipContents</code>
3911          * property.
3912          * @exception IllegalStateException if the buffers have not yet
3913          * been created
3914          * @see java.awt.BufferCapabilities#getFlipContents()
3915          */
3916         protected void flip(BufferCapabilities.FlipContents flipAction) {
3917             if (peer != null) {
3918                 Image backBuffer = getBackBuffer();
3919                 if (backBuffer != null) {
3920                     peer.flip(0, 0,
3921                               backBuffer.getWidth(null),
3922                               backBuffer.getHeight(null), flipAction);
3923                 }
3924             } else {
3925                 throw new IllegalStateException(
3926                     "Component must have a valid peer");
3927             }
3928         }
3929 
3930         void flipSubRegion(int x1, int y1, int x2, int y2,
3931                       BufferCapabilities.FlipContents flipAction)
3932         {
3933             if (peer != null) {
3934                 peer.flip(x1, y1, x2, y2, flipAction);
3935             } else {
3936                 throw new IllegalStateException(
3937                     "Component must have a valid peer");
3938             }
3939         }
3940 
3941         /**
3942          * Destroys the buffers created through this object
3943          */
3944         protected void destroyBuffers() {
3945             VSyncedBSManager.releaseVsync(this);
3946             if (peer != null) {
3947                 peer.destroyBuffers();
3948             } else {
3949                 throw new IllegalStateException(
3950                     "Component must have a valid peer");
3951             }
3952         }
3953 
3954         /**
3955          * @return the buffering capabilities of this strategy
3956          */
3957         public BufferCapabilities getCapabilities() {
3958             if (caps instanceof ProxyCapabilities) {
3959                 return ((ProxyCapabilities)caps).orig;
3960             } else {
3961                 return caps;
3962             }
3963         }
3964 
3965         /**
3966          * @return the graphics on the drawing buffer.  This method may not
3967          * be synchronized for performance reasons; use of this method by multiple
3968          * threads should be handled at the application level.  Disposal of the
3969          * graphics object must be handled by the application.
3970          */
3971         public Graphics getDrawGraphics() {
3972             revalidate();
3973             return drawBuffer.getGraphics();
3974         }
3975 
3976         /**
3977          * Restore the drawing buffer if it has been lost
3978          */
3979         protected void revalidate() {
3980             revalidate(true);
3981         }
3982 
3983         void revalidate(boolean checkSize) {
3984             validatedContents = false;
3985 
3986             if (checkSize && (getWidth() != width || getHeight() != height)) {
3987                 // component has been resized; recreate the backbuffers
3988                 try {
3989                     createBuffers(numBuffers, caps);
3990                 } catch (AWTException e) {
3991                     // shouldn't be possible
3992                 }
3993                 validatedContents = true;
3994             }
3995 
3996             // get the buffers from the peer every time since they
3997             // might have been replaced in response to a display change event
3998             updateInternalBuffers();
3999 
4000             // now validate the backbuffer
4001             if (drawVBuffer != null) {
4002                 GraphicsConfiguration gc =
4003                         getGraphicsConfiguration_NoClientCode();
4004                 int returnCode = drawVBuffer.validate(gc);
4005                 if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) {
4006                     try {
4007                         createBuffers(numBuffers, caps);
4008                     } catch (AWTException e) {
4009                         // shouldn't be possible
4010                     }
4011                     if (drawVBuffer != null) {
4012                         // backbuffers were recreated, so validate again
4013                         drawVBuffer.validate(gc);
4014                     }
4015                     validatedContents = true;
4016                 } else if (returnCode == VolatileImage.IMAGE_RESTORED) {
4017                     validatedContents = true;
4018                 }
4019             }
4020         }
4021 
4022         /**
4023          * @return whether the drawing buffer was lost since the last call to
4024          * <code>getDrawGraphics</code>
4025          */
4026         public boolean contentsLost() {
4027             if (drawVBuffer == null) {
4028                 return false;
4029             }
4030             return drawVBuffer.contentsLost();
4031         }
4032 
4033         /**
4034          * @return whether the drawing buffer was recently restored from a lost
4035          * state and reinitialized to the default background color (white)
4036          */
4037         public boolean contentsRestored() {
4038             return validatedContents;
4039         }
4040 
4041         /**
4042          * Makes the next available buffer visible by either blitting or
4043          * flipping.
4044          */
4045         public void show() {
4046             flip(caps.getFlipContents());
4047         }
4048 
4049         /**
4050          * Makes specified region of the the next available buffer visible
4051          * by either blitting or flipping.
4052          */
4053         void showSubRegion(int x1, int y1, int x2, int y2) {
4054             flipSubRegion(x1, y1, x2, y2, caps.getFlipContents());
4055         }
4056 
4057         /**
4058          * {@inheritDoc}
4059          * @since 1.6
4060          */
4061         public void dispose() {
4062             if (Component.this.bufferStrategy == this) {
4063                 Component.this.bufferStrategy = null;
4064                 if (peer != null) {
4065                     destroyBuffers();
4066                 }
4067             }
4068         }
4069 
4070     } // Inner class FlipBufferStrategy
4071 
4072     /**
4073      * Inner class for blitting offscreen surfaces to a component.
4074      *
4075      * @author Michael Martak
4076      * @since 1.4
4077      */
4078     protected class BltBufferStrategy extends BufferStrategy {
4079 
4080         /**
4081          * The buffering capabilities
4082          */
4083         protected BufferCapabilities caps; // = null
4084         /**
4085          * The back buffers
4086          */
4087         protected VolatileImage[] backBuffers; // = null
4088         /**
4089          * Whether or not the drawing buffer has been recently restored from
4090          * a lost state.
4091          */
4092         protected boolean validatedContents; // = false
4093         /**
4094          * Size of the back buffers
4095          */
4096         protected int width;
4097         protected int height;
4098 
4099         /**
4100          * Insets for the hosting Component.  The size of the back buffer
4101          * is constrained by these.
4102          */
4103         private Insets insets;
4104 
4105         /**
4106          * Creates a new blt buffer strategy around a component
4107          * @param numBuffers number of buffers to create, including the
4108          * front buffer
4109          * @param caps the capabilities of the buffers
4110          */
4111         protected BltBufferStrategy(int numBuffers, BufferCapabilities caps) {
4112             this.caps = caps;
4113             createBackBuffers(numBuffers - 1);
4114         }
4115 
4116         /**
4117          * {@inheritDoc}
4118          * @since 1.6
4119          */
4120         public void dispose() {
4121             if (backBuffers != null) {
4122                 for (int counter = backBuffers.length - 1; counter >= 0;
4123                      counter--) {
4124                     if (backBuffers[counter] != null) {
4125                         backBuffers[counter].flush();
4126                         backBuffers[counter] = null;
4127                     }
4128                 }
4129             }
4130             if (Component.this.bufferStrategy == this) {
4131                 Component.this.bufferStrategy = null;
4132             }
4133         }
4134 
4135         /**
4136          * Creates the back buffers
4137          */
4138         protected void createBackBuffers(int numBuffers) {
4139             if (numBuffers == 0) {
4140                 backBuffers = null;
4141             } else {
4142                 // save the current bounds
4143                 width = getWidth();
4144                 height = getHeight();
4145                 insets = getInsets_NoClientCode();
4146                 int iWidth = width - insets.left - insets.right;
4147                 int iHeight = height - insets.top - insets.bottom;
4148 
4149                 // It is possible for the component's width and/or height
4150                 // to be 0 here.  Force the size of the backbuffers to
4151                 // be > 0 so that creating the image won't fail.
4152                 iWidth = Math.max(1, iWidth);
4153                 iHeight = Math.max(1, iHeight);
4154                 if (backBuffers == null) {
4155                     backBuffers = new VolatileImage[numBuffers];
4156                 } else {
4157                     // flush any existing backbuffers
4158                     for (int i = 0; i < numBuffers; i++) {
4159                         if (backBuffers[i] != null) {
4160                             backBuffers[i].flush();
4161                             backBuffers[i] = null;
4162                         }
4163                     }
4164                 }
4165 
4166                 // create the backbuffers
4167                 for (int i = 0; i < numBuffers; i++) {
4168                     backBuffers[i] = createVolatileImage(iWidth, iHeight);
4169                 }
4170             }
4171         }
4172 
4173         /**
4174          * @return the buffering capabilities of this strategy
4175          */
4176         public BufferCapabilities getCapabilities() {
4177             return caps;
4178         }
4179 
4180         /**
4181          * @return the draw graphics
4182          */
4183         public Graphics getDrawGraphics() {
4184             revalidate();
4185             Image backBuffer = getBackBuffer();
4186             if (backBuffer == null) {
4187                 return getGraphics();
4188             }
4189             SunGraphics2D g = (SunGraphics2D)backBuffer.getGraphics();
4190             g.constrain(-insets.left, -insets.top,
4191                         backBuffer.getWidth(null) + insets.left,
4192                         backBuffer.getHeight(null) + insets.top);
4193             return g;
4194         }
4195 
4196         /**
4197          * @return direct access to the back buffer, as an image.
4198          * If there is no back buffer, returns null.
4199          */
4200         Image getBackBuffer() {
4201             if (backBuffers != null) {
4202                 return backBuffers[backBuffers.length - 1];
4203             } else {
4204                 return null;
4205             }
4206         }
4207 
4208         /**
4209          * Makes the next available buffer visible.
4210          */
4211         public void show() {
4212             showSubRegion(insets.left, insets.top,
4213                           width - insets.right,
4214                           height - insets.bottom);
4215         }
4216 
4217         /**
4218          * Package-private method to present a specific rectangular area
4219          * of this buffer.  This class currently shows only the entire
4220          * buffer, by calling showSubRegion() with the full dimensions of
4221          * the buffer.  Subclasses (e.g., BltSubRegionBufferStrategy
4222          * and FlipSubRegionBufferStrategy) may have region-specific show
4223          * methods that call this method with actual sub regions of the
4224          * buffer.
4225          */
4226         void showSubRegion(int x1, int y1, int x2, int y2) {
4227             if (backBuffers == null) {
4228                 return;
4229             }
4230             // Adjust location to be relative to client area.
4231             x1 -= insets.left;
4232             x2 -= insets.left;
4233             y1 -= insets.top;
4234             y2 -= insets.top;
4235             Graphics g = getGraphics_NoClientCode();
4236             if (g == null) {
4237                 // Not showing, bail
4238                 return;
4239             }
4240             try {
4241                 // First image copy is in terms of Frame's coordinates, need
4242                 // to translate to client area.
4243                 g.translate(insets.left, insets.top);
4244                 for (int i = 0; i < backBuffers.length; i++) {
4245                     g.drawImage(backBuffers[i],
4246                                 x1, y1, x2, y2,
4247                                 x1, y1, x2, y2,
4248                                 null);
4249                     g.dispose();
4250                     g = null;
4251                     g = backBuffers[i].getGraphics();
4252                 }
4253             } finally {
4254                 if (g != null) {
4255                     g.dispose();
4256                 }
4257             }
4258         }
4259 
4260         /**
4261          * Restore the drawing buffer if it has been lost
4262          */
4263         protected void revalidate() {
4264             revalidate(true);
4265         }
4266 
4267         void revalidate(boolean checkSize) {
4268             validatedContents = false;
4269 
4270             if (backBuffers == null) {
4271                 return;
4272             }
4273 
4274             if (checkSize) {
4275                 Insets insets = getInsets_NoClientCode();
4276                 if (getWidth() != width || getHeight() != height ||
4277                     !insets.equals(this.insets)) {
4278                     // component has been resized; recreate the backbuffers
4279                     createBackBuffers(backBuffers.length);
4280                     validatedContents = true;
4281                 }
4282             }
4283 
4284             // now validate the backbuffer
4285             GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode();
4286             int returnCode =
4287                 backBuffers[backBuffers.length - 1].validate(gc);
4288             if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) {
4289                 if (checkSize) {
4290                     createBackBuffers(backBuffers.length);
4291                     // backbuffers were recreated, so validate again
4292                     backBuffers[backBuffers.length - 1].validate(gc);
4293                 }
4294                 // else case means we're called from Swing on the toolkit
4295                 // thread, don't recreate buffers as that'll deadlock
4296                 // (creating VolatileImages invokes getting GraphicsConfig
4297                 // which grabs treelock).
4298                 validatedContents = true;
4299             } else if (returnCode == VolatileImage.IMAGE_RESTORED) {
4300                 validatedContents = true;
4301             }
4302         }
4303 
4304         /**
4305          * @return whether the drawing buffer was lost since the last call to
4306          * <code>getDrawGraphics</code>
4307          */
4308         public boolean contentsLost() {
4309             if (backBuffers == null) {
4310                 return false;
4311             } else {
4312                 return backBuffers[backBuffers.length - 1].contentsLost();
4313             }
4314         }
4315 
4316         /**
4317          * @return whether the drawing buffer was recently restored from a lost
4318          * state and reinitialized to the default background color (white)
4319          */
4320         public boolean contentsRestored() {
4321             return validatedContents;
4322         }
4323     } // Inner class BltBufferStrategy
4324 
4325     /**
4326      * Private class to perform sub-region flipping.
4327      */
4328     private class FlipSubRegionBufferStrategy extends FlipBufferStrategy
4329         implements SubRegionShowable
4330     {
4331 
4332         protected FlipSubRegionBufferStrategy(int numBuffers,
4333                                               BufferCapabilities caps)
4334             throws AWTException
4335         {
4336             super(numBuffers, caps);
4337         }
4338 
4339         public void show(int x1, int y1, int x2, int y2) {
4340             showSubRegion(x1, y1, x2, y2);
4341         }
4342 
4343         // This is invoked by Swing on the toolkit thread.
4344         public boolean showIfNotLost(int x1, int y1, int x2, int y2) {
4345             if (!contentsLost()) {
4346                 showSubRegion(x1, y1, x2, y2);
4347                 return !contentsLost();
4348             }
4349             return false;
4350         }
4351     }
4352 
4353     /**
4354      * Private class to perform sub-region blitting.  Swing will use
4355      * this subclass via the SubRegionShowable interface in order to
4356      * copy only the area changed during a repaint.
4357      * @see javax.swing.BufferStrategyPaintManager
4358      */
4359     private class BltSubRegionBufferStrategy extends BltBufferStrategy
4360         implements SubRegionShowable
4361     {
4362 
4363         protected BltSubRegionBufferStrategy(int numBuffers,
4364                                              BufferCapabilities caps)
4365         {
4366             super(numBuffers, caps);
4367         }
4368 
4369         public void show(int x1, int y1, int x2, int y2) {
4370             showSubRegion(x1, y1, x2, y2);
4371         }
4372 
4373         // This method is called by Swing on the toolkit thread.
4374         public boolean showIfNotLost(int x1, int y1, int x2, int y2) {
4375             if (!contentsLost()) {
4376                 showSubRegion(x1, y1, x2, y2);
4377                 return !contentsLost();
4378             }
4379             return false;
4380         }
4381     }
4382 
4383     /**
4384      * Inner class for flipping buffers on a component.  That component must
4385      * be a <code>Canvas</code> or <code>Window</code>.
4386      * @see Canvas
4387      * @see Window
4388      * @see java.awt.image.BufferStrategy
4389      * @author Michael Martak
4390      * @since 1.4
4391      */
4392     private class SingleBufferStrategy extends BufferStrategy {
4393 
4394         private BufferCapabilities caps;
4395 
4396         public SingleBufferStrategy(BufferCapabilities caps) {
4397             this.caps = caps;
4398         }
4399         public BufferCapabilities getCapabilities() {
4400             return caps;
4401         }
4402         public Graphics getDrawGraphics() {
4403             return getGraphics();
4404         }
4405         public boolean contentsLost() {
4406             return false;
4407         }
4408         public boolean contentsRestored() {
4409             return false;
4410         }
4411         public void show() {
4412             // Do nothing
4413         }
4414     } // Inner class SingleBufferStrategy
4415 
4416     /**
4417      * Sets whether or not paint messages received from the operating system
4418      * should be ignored.  This does not affect paint events generated in
4419      * software by the AWT, unless they are an immediate response to an
4420      * OS-level paint message.
4421      * <p>
4422      * This is useful, for example, if running under full-screen mode and
4423      * better performance is desired, or if page-flipping is used as the
4424      * buffer strategy.
4425      *
4426      * @since 1.4
4427      * @see #getIgnoreRepaint
4428      * @see Canvas#createBufferStrategy
4429      * @see Window#createBufferStrategy
4430      * @see java.awt.image.BufferStrategy
4431      * @see GraphicsDevice#setFullScreenWindow
4432      */
4433     public void setIgnoreRepaint(boolean ignoreRepaint) {
4434         this.ignoreRepaint = ignoreRepaint;
4435     }
4436 
4437     /**
4438      * @return whether or not paint messages received from the operating system
4439      * should be ignored.
4440      *
4441      * @since 1.4
4442      * @see #setIgnoreRepaint
4443      */
4444     public boolean getIgnoreRepaint() {
4445         return ignoreRepaint;
4446     }
4447 
4448     /**
4449      * Checks whether this component "contains" the specified point,
4450      * where <code>x</code> and <code>y</code> are defined to be
4451      * relative to the coordinate system of this component.
4452      * @param     x   the <i>x</i> coordinate of the point
4453      * @param     y   the <i>y</i> coordinate of the point
4454      * @see       #getComponentAt(int, int)
4455      * @since     JDK1.1
4456      */
4457     public boolean contains(int x, int y) {
4458         return inside(x, y);
4459     }
4460 
4461     /**
4462      * @deprecated As of JDK version 1.1,
4463      * replaced by contains(int, int).
4464      */
4465     @Deprecated
4466     public boolean inside(int x, int y) {
4467         return (x >= 0) && (x < width) && (y >= 0) && (y < height);
4468     }
4469 
4470     /**
4471      * Checks whether this component "contains" the specified point,
4472      * where the point's <i>x</i> and <i>y</i> coordinates are defined
4473      * to be relative to the coordinate system of this component.
4474      * @param     p     the point
4475      * @see       #getComponentAt(Point)
4476      * @since     JDK1.1
4477      */
4478     public boolean contains(Point p) {
4479         return contains(p.x, p.y);
4480     }
4481 
4482     /**
4483      * Determines if this component or one of its immediate
4484      * subcomponents contains the (<i>x</i>,&nbsp;<i>y</i>) location,
4485      * and if so, returns the containing component. This method only
4486      * looks one level deep. If the point (<i>x</i>,&nbsp;<i>y</i>) is
4487      * inside a subcomponent that itself has subcomponents, it does not
4488      * go looking down the subcomponent tree.
4489      * <p>
4490      * The <code>locate</code> method of <code>Component</code> simply
4491      * returns the component itself if the (<i>x</i>,&nbsp;<i>y</i>)
4492      * coordinate location is inside its bounding box, and <code>null</code>
4493      * otherwise.
4494      * @param     x   the <i>x</i> coordinate
4495      * @param     y   the <i>y</i> coordinate
4496      * @return    the component or subcomponent that contains the
4497      *                (<i>x</i>,&nbsp;<i>y</i>) location;
4498      *                <code>null</code> if the location
4499      *                is outside this component
4500      * @see       #contains(int, int)
4501      * @since     JDK1.0
4502      */
4503     public Component getComponentAt(int x, int y) {
4504         return locate(x, y);
4505     }
4506 
4507     /**
4508      * @deprecated As of JDK version 1.1,
4509      * replaced by getComponentAt(int, int).
4510      */
4511     @Deprecated
4512     public Component locate(int x, int y) {
4513         return contains(x, y) ? this : null;
4514     }
4515 
4516     /**
4517      * Returns the component or subcomponent that contains the
4518      * specified point.
4519      * @param     p   the point
4520      * @see       java.awt.Component#contains
4521      * @since     JDK1.1
4522      */
4523     public Component getComponentAt(Point p) {
4524         return getComponentAt(p.x, p.y);
4525     }
4526 
4527     /**
4528      * @deprecated As of JDK version 1.1,
4529      * replaced by <code>dispatchEvent(AWTEvent e)</code>.
4530      */
4531     @Deprecated
4532     public void deliverEvent(Event e) {
4533         postEvent(e);
4534     }
4535 
4536     /**
4537      * Dispatches an event to this component or one of its sub components.
4538      * Calls <code>processEvent</code> before returning for 1.1-style
4539      * events which have been enabled for the <code>Component</code>.
4540      * @param e the event
4541      */
4542     public final void dispatchEvent(AWTEvent e) {
4543         dispatchEventImpl(e);
4544     }
4545 
4546     void dispatchEventImpl(AWTEvent e) {
4547         int id = e.getID();
4548 
4549         // Check that this component belongs to this app-context
4550         AppContext compContext = appContext;
4551         if (compContext != null && !compContext.equals(AppContext.getAppContext())) {
4552             if (eventLog.isLoggable(Level.FINE)) {
4553                 eventLog.log(Level.FINE, "Event " + e + " is being dispatched on the wrong AppContext");
4554             }
4555         }
4556 
4557         if (eventLog.isLoggable(Level.FINEST)) {
4558             eventLog.log(Level.FINEST, "{0}", e);
4559         }
4560 
4561         /*
4562          * 0. Set timestamp and modifiers of current event.
4563          */
4564         EventQueue.setCurrentEventAndMostRecentTime(e);
4565 
4566         /*
4567          * 1. Pre-dispatchers. Do any necessary retargeting/reordering here
4568          *    before we notify AWTEventListeners.
4569          */
4570 
4571         if (e instanceof SunDropTargetEvent) {
4572             ((SunDropTargetEvent)e).dispatch();
4573             return;
4574         }
4575 
4576         if (!e.focusManagerIsDispatching) {
4577             // Invoke the private focus retargeting method which provides
4578             // lightweight Component support
4579             if (e.isPosted) {
4580                 e = KeyboardFocusManager.retargetFocusEvent(e);
4581                 e.isPosted = true;
4582             }
4583 
4584             // Now, with the event properly targeted to a lightweight
4585             // descendant if necessary, invoke the public focus retargeting
4586             // and dispatching function
4587             if (KeyboardFocusManager.getCurrentKeyboardFocusManager().
4588                 dispatchEvent(e))
4589             {
4590                 return;
4591             }
4592         }
4593         if ((e instanceof FocusEvent) && focusLog.isLoggable(Level.FINEST)) {
4594             focusLog.log(Level.FINEST, "" + e);
4595         }
4596         // MouseWheel may need to be retargeted here so that
4597         // AWTEventListener sees the event go to the correct
4598         // Component.  If the MouseWheelEvent needs to go to an ancestor,
4599         // the event is dispatched to the ancestor, and dispatching here
4600         // stops.
4601         if (id == MouseEvent.MOUSE_WHEEL &&
4602             (!eventTypeEnabled(id)) &&
4603             (peer != null && !peer.handlesWheelScrolling()) &&
4604             (dispatchMouseWheelToAncestor((MouseWheelEvent)e)))
4605         {
4606             return;
4607         }
4608 
4609         /*
4610          * 2. Allow the Toolkit to pass this to AWTEventListeners.
4611          */
4612         Toolkit toolkit = Toolkit.getDefaultToolkit();
4613         toolkit.notifyAWTEventListeners(e);
4614 
4615 
4616         /*
4617          * 3. If no one has consumed a key event, allow the
4618          *    KeyboardFocusManager to process it.
4619          */
4620         if (!e.isConsumed()) {
4621             if (e instanceof java.awt.event.KeyEvent) {
4622                 KeyboardFocusManager.getCurrentKeyboardFocusManager().
4623                     processKeyEvent(this, (KeyEvent)e);
4624                 if (e.isConsumed()) {
4625                     return;
4626                 }
4627             }
4628         }
4629 
4630         /*
4631          * 4. Allow input methods to process the event
4632          */
4633         if (areInputMethodsEnabled()) {
4634             // We need to pass on InputMethodEvents since some host
4635             // input method adapters send them through the Java
4636             // event queue instead of directly to the component,
4637             // and the input context also handles the Java composition window
4638             if(((e instanceof InputMethodEvent) && !(this instanceof CompositionArea))
4639                ||
4640                // Otherwise, we only pass on input and focus events, because
4641                // a) input methods shouldn't know about semantic or component-level events
4642                // b) passing on the events takes time
4643                // c) isConsumed() is always true for semantic events.
4644                (e instanceof InputEvent) || (e instanceof FocusEvent)) {
4645                 InputContext inputContext = getInputContext();
4646 
4647 
4648                 if (inputContext != null) {
4649                     inputContext.dispatchEvent(e);
4650                     if (e.isConsumed()) {
4651                         if ((e instanceof FocusEvent) && focusLog.isLoggable(Level.FINEST)) {
4652                             focusLog.log(Level.FINEST, "3579: Skipping " + e);
4653                         }
4654                         return;
4655                     }
4656                 }
4657             }
4658         } else {
4659             // When non-clients get focus, we need to explicitly disable the native
4660             // input method. The native input method is actually not disabled when
4661             // the active/passive/peered clients loose focus.
4662             if (id == FocusEvent.FOCUS_GAINED) {
4663                 InputContext inputContext = getInputContext();
4664                 if (inputContext != null && inputContext instanceof sun.awt.im.InputContext) {
4665                     ((sun.awt.im.InputContext)inputContext).disableNativeIM();
4666                 }
4667             }
4668         }
4669 
4670 
4671         /*
4672          * 5. Pre-process any special events before delivery
4673          */
4674         switch(id) {
4675             // Handling of the PAINT and UPDATE events is now done in the
4676             // peer's handleEvent() method so the background can be cleared
4677             // selectively for non-native components on Windows only.
4678             // - Fred.Ecks@Eng.sun.com, 5-8-98
4679 
4680           case KeyEvent.KEY_PRESSED:
4681           case KeyEvent.KEY_RELEASED:
4682               Container p = (Container)((this instanceof Container) ? this : parent);
4683               if (p != null) {
4684                   p.preProcessKeyEvent((KeyEvent)e);
4685                   if (e.isConsumed()) {
4686                         if (focusLog.isLoggable(Level.FINEST)) {
4687                             focusLog.log(Level.FINEST, "Pre-process consumed event");
4688                         }
4689                       return;
4690                   }
4691               }
4692               break;
4693 
4694           case WindowEvent.WINDOW_CLOSING:
4695               if (toolkit instanceof WindowClosingListener) {
4696                   windowClosingException = ((WindowClosingListener)
4697                                             toolkit).windowClosingNotify((WindowEvent)e);
4698                   if (checkWindowClosingException()) {
4699                       return;
4700                   }
4701               }
4702               break;
4703 
4704           default:
4705               break;
4706         }
4707 
4708         /*
4709          * 6. Deliver event for normal processing
4710          */
4711         if (newEventsOnly) {
4712             // Filtering needs to really be moved to happen at a lower
4713             // level in order to get maximum performance gain;  it is
4714             // here temporarily to ensure the API spec is honored.
4715             //
4716             if (eventEnabled(e)) {
4717                 processEvent(e);
4718             }
4719         } else if (id == MouseEvent.MOUSE_WHEEL) {
4720             // newEventsOnly will be false for a listenerless ScrollPane, but
4721             // MouseWheelEvents still need to be dispatched to it so scrolling
4722             // can be done.
4723             autoProcessMouseWheel((MouseWheelEvent)e);
4724         } else if (!(e instanceof MouseEvent && !postsOldMouseEvents())) {
4725             //
4726             // backward compatibility
4727             //
4728             Event olde = e.convertToOld();
4729             if (olde != null) {
4730                 int key = olde.key;
4731                 int modifiers = olde.modifiers;
4732 
4733                 postEvent(olde);
4734                 if (olde.isConsumed()) {
4735                     e.consume();
4736                 }
4737                 // if target changed key or modifier values, copy them
4738                 // back to original event
4739                 //
4740                 switch(olde.id) {
4741                   case Event.KEY_PRESS:
4742                   case Event.KEY_RELEASE:
4743                   case Event.KEY_ACTION:
4744                   case Event.KEY_ACTION_RELEASE:
4745                       if (olde.key != key) {
4746                           ((KeyEvent)e).setKeyChar(olde.getKeyEventChar());
4747                       }
4748                       if (olde.modifiers != modifiers) {
4749                           ((KeyEvent)e).setModifiers(olde.modifiers);
4750                       }
4751                       break;
4752                   default:
4753                       break;
4754                 }
4755             }
4756         }
4757 
4758         /*
4759          * 8. Special handling for 4061116 : Hook for browser to close modal
4760          *    dialogs.
4761          */
4762         if (id == WindowEvent.WINDOW_CLOSING && !e.isConsumed()) {
4763             if (toolkit instanceof WindowClosingListener) {
4764                 windowClosingException =
4765                     ((WindowClosingListener)toolkit).
4766                     windowClosingDelivered((WindowEvent)e);
4767                 if (checkWindowClosingException()) {
4768                     return;
4769                 }
4770             }
4771         }
4772 
4773         /*
4774          * 9. Allow the peer to process the event.
4775          * Except KeyEvents, they will be processed by peer after
4776          * all KeyEventPostProcessors
4777          * (see DefaultKeyboardFocusManager.dispatchKeyEvent())
4778          */
4779         if (!(e instanceof KeyEvent)) {
4780             ComponentPeer tpeer = peer;
4781             if (e instanceof FocusEvent && (tpeer == null || tpeer instanceof LightweightPeer)) {
4782                 // if focus owner is lightweight then its native container
4783                 // processes event
4784                 Component source = (Component)e.getSource();
4785                 if (source != null) {
4786                     Container target = source.getNativeContainer();
4787                     if (target != null) {
4788                         tpeer = target.getPeer();
4789                     }
4790                 }
4791             }
4792             if (tpeer != null) {
4793                 tpeer.handleEvent(e);
4794             }
4795         }
4796     } // dispatchEventImpl()
4797 
4798     /*
4799      * If newEventsOnly is false, method is called so that ScrollPane can
4800      * override it and handle common-case mouse wheel scrolling.  NOP
4801      * for Component.
4802      */
4803     void autoProcessMouseWheel(MouseWheelEvent e) {}
4804 
4805     /*
4806      * Dispatch given MouseWheelEvent to the first ancestor for which
4807      * MouseWheelEvents are enabled.
4808      *
4809      * Returns whether or not event was dispatched to an ancestor
4810      */
4811     boolean dispatchMouseWheelToAncestor(MouseWheelEvent e) {
4812         int newX, newY;
4813         newX = e.getX() + getX(); // Coordinates take into account at least
4814         newY = e.getY() + getY(); // the cursor's position relative to this
4815                                   // Component (e.getX()), and this Component's
4816                                   // position relative to its parent.
4817         MouseWheelEvent newMWE;
4818 
4819         if (eventLog.isLoggable(Level.FINEST)) {
4820             eventLog.log(Level.FINEST, "dispatchMouseWheelToAncestor");
4821             eventLog.log(Level.FINEST, "orig event src is of " + e.getSource().getClass());
4822         }
4823 
4824         /* parent field for Window refers to the owning Window.
4825          * MouseWheelEvents should NOT be propagated into owning Windows
4826          */
4827         synchronized (getTreeLock()) {
4828             Container anc = getParent();
4829             while (anc != null && !anc.eventEnabled(e)) {
4830                 // fix coordinates to be relative to new event source
4831                 newX += anc.getX();
4832                 newY += anc.getY();
4833 
4834                 if (!(anc instanceof Window)) {
4835                     anc = anc.getParent();
4836                 }
4837                 else {
4838                     break;
4839                 }
4840             }
4841 
4842             if (eventLog.isLoggable(Level.FINEST)) {
4843                 eventLog.log(Level.FINEST, "new event src is " + anc.getClass());
4844             }
4845 
4846             if (anc != null && anc.eventEnabled(e)) {
4847                 // Change event to be from new source, with new x,y
4848                 // For now, just create a new event - yucky
4849 
4850                 newMWE = new MouseWheelEvent(anc, // new source
4851                                              e.getID(),
4852                                              e.getWhen(),
4853                                              e.getModifiers(),
4854                                              newX, // x relative to new source
4855                                              newY, // y relative to new source
4856                                              e.getXOnScreen(),
4857                                              e.getYOnScreen(),
4858                                              e.getClickCount(),
4859                                              e.isPopupTrigger(),
4860                                              e.getScrollType(),
4861                                              e.getScrollAmount(),
4862                                              e.getWheelRotation(),
4863                                              e.getPreciseWheelRotation());
4864                 ((AWTEvent)e).copyPrivateDataInto(newMWE);
4865                 // When dispatching a wheel event to
4866                 // ancestor, there is no need trying to find descendant
4867                 // lightweights to dispatch event to.
4868                 // If we dispatch the event to toplevel ancestor,
4869                 // this could encolse the loop: 6480024.
4870                 anc.dispatchEventToSelf(newMWE);
4871             }
4872         }
4873         return true;
4874     }
4875 
4876     boolean checkWindowClosingException() {
4877         if (windowClosingException != null) {
4878             if (this instanceof Dialog) {
4879                 ((Dialog)this).interruptBlocking();
4880             } else {
4881                 windowClosingException.fillInStackTrace();
4882                 windowClosingException.printStackTrace();
4883                 windowClosingException = null;
4884             }
4885             return true;
4886         }
4887         return false;
4888     }
4889 
4890     boolean areInputMethodsEnabled() {
4891         // in 1.2, we assume input method support is required for all
4892         // components that handle key events, but components can turn off
4893         // input methods by calling enableInputMethods(false).
4894         return ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) &&
4895             ((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 || keyListener != null);
4896     }
4897 
4898     // REMIND: remove when filtering is handled at lower level
4899     boolean eventEnabled(AWTEvent e) {
4900         return eventTypeEnabled(e.id);
4901     }
4902 
4903     boolean eventTypeEnabled(int type) {
4904         switch(type) {
4905           case ComponentEvent.COMPONENT_MOVED:
4906           case ComponentEvent.COMPONENT_RESIZED:
4907           case ComponentEvent.COMPONENT_SHOWN:
4908           case ComponentEvent.COMPONENT_HIDDEN:
4909               if ((eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||
4910                   componentListener != null) {
4911                   return true;
4912               }
4913               break;
4914           case FocusEvent.FOCUS_GAINED:
4915           case FocusEvent.FOCUS_LOST:
4916               if ((eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0 ||
4917                   focusListener != null) {
4918                   return true;
4919               }
4920               break;
4921           case KeyEvent.KEY_PRESSED:
4922           case KeyEvent.KEY_RELEASED:
4923           case KeyEvent.KEY_TYPED:
4924               if ((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 ||
4925                   keyListener != null) {
4926                   return true;
4927               }
4928               break;
4929           case MouseEvent.MOUSE_PRESSED:
4930           case MouseEvent.MOUSE_RELEASED:
4931           case MouseEvent.MOUSE_ENTERED:
4932           case MouseEvent.MOUSE_EXITED:
4933           case MouseEvent.MOUSE_CLICKED:
4934               if ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0 ||
4935                   mouseListener != null) {
4936                   return true;
4937               }
4938               break;
4939           case MouseEvent.MOUSE_MOVED:
4940           case MouseEvent.MOUSE_DRAGGED:
4941               if ((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0 ||
4942                   mouseMotionListener != null) {
4943                   return true;
4944               }
4945               break;
4946           case MouseEvent.MOUSE_WHEEL:
4947               if ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0 ||
4948                   mouseWheelListener != null) {
4949                   return true;
4950               }
4951               break;
4952           case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED:
4953           case InputMethodEvent.CARET_POSITION_CHANGED:
4954               if ((eventMask & AWTEvent.INPUT_METHOD_EVENT_MASK) != 0 ||
4955                   inputMethodListener != null) {
4956                   return true;
4957               }
4958               break;
4959           case HierarchyEvent.HIERARCHY_CHANGED:
4960               if ((eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
4961                   hierarchyListener != null) {
4962                   return true;
4963               }
4964               break;
4965           case HierarchyEvent.ANCESTOR_MOVED:
4966           case HierarchyEvent.ANCESTOR_RESIZED:
4967               if ((eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 ||
4968                   hierarchyBoundsListener != null) {
4969                   return true;
4970               }
4971               break;
4972           case ActionEvent.ACTION_PERFORMED:
4973               if ((eventMask & AWTEvent.ACTION_EVENT_MASK) != 0) {
4974                   return true;
4975               }
4976               break;
4977           case TextEvent.TEXT_VALUE_CHANGED:
4978               if ((eventMask & AWTEvent.TEXT_EVENT_MASK) != 0) {
4979                   return true;
4980               }
4981               break;
4982           case ItemEvent.ITEM_STATE_CHANGED:
4983               if ((eventMask & AWTEvent.ITEM_EVENT_MASK) != 0) {
4984                   return true;
4985               }
4986               break;
4987           case AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED:
4988               if ((eventMask & AWTEvent.ADJUSTMENT_EVENT_MASK) != 0) {
4989                   return true;
4990               }
4991               break;
4992           default:
4993               break;
4994         }
4995         //
4996         // Always pass on events defined by external programs.
4997         //
4998         if (type > AWTEvent.RESERVED_ID_MAX) {
4999             return true;
5000         }
5001         return false;
5002     }
5003 
5004     /**
5005      * @deprecated As of JDK version 1.1,
5006      * replaced by dispatchEvent(AWTEvent).
5007      */
5008     @Deprecated
5009     public boolean postEvent(Event e) {
5010         ComponentPeer peer = this.peer;
5011 
5012         if (handleEvent(e)) {
5013             e.consume();
5014             return true;
5015         }
5016 
5017         Component parent = this.parent;
5018         int eventx = e.x;
5019         int eventy = e.y;
5020         if (parent != null) {
5021             e.translate(x, y);
5022             if (parent.postEvent(e)) {
5023                 e.consume();
5024                 return true;
5025             }
5026             // restore coords
5027             e.x = eventx;
5028             e.y = eventy;
5029         }
5030         return false;
5031     }
5032 
5033     // Event source interfaces
5034 
5035     /**
5036      * Adds the specified component listener to receive component events from
5037      * this component.
5038      * If listener <code>l</code> is <code>null</code>,
5039      * no exception is thrown and no action is performed.
5040      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5041      * >AWT Threading Issues</a> for details on AWT's threading model.
5042      *
5043      * @param    l   the component listener
5044      * @see      java.awt.event.ComponentEvent
5045      * @see      java.awt.event.ComponentListener
5046      * @see      #removeComponentListener
5047      * @see      #getComponentListeners
5048      * @since    JDK1.1
5049      */
5050     public synchronized void addComponentListener(ComponentListener l) {
5051         if (l == null) {
5052             return;
5053         }
5054         componentListener = AWTEventMulticaster.add(componentListener, l);
5055         newEventsOnly = true;
5056     }
5057 
5058     /**
5059      * Removes the specified component listener so that it no longer
5060      * receives component events from this component. This method performs
5061      * no function, nor does it throw an exception, if the listener
5062      * specified by the argument was not previously added to this component.
5063      * If listener <code>l</code> is <code>null</code>,
5064      * no exception is thrown and no action is performed.
5065      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5066      * >AWT Threading Issues</a> for details on AWT's threading model.
5067      * @param    l   the component listener
5068      * @see      java.awt.event.ComponentEvent
5069      * @see      java.awt.event.ComponentListener
5070      * @see      #addComponentListener
5071      * @see      #getComponentListeners
5072      * @since    JDK1.1
5073      */
5074     public synchronized void removeComponentListener(ComponentListener l) {
5075         if (l == null) {
5076             return;
5077         }
5078         componentListener = AWTEventMulticaster.remove(componentListener, l);
5079     }
5080 
5081     /**
5082      * Returns an array of all the component listeners
5083      * registered on this component.
5084      *
5085      * @return all of this comonent's <code>ComponentListener</code>s
5086      *         or an empty array if no component
5087      *         listeners are currently registered
5088      *
5089      * @see #addComponentListener
5090      * @see #removeComponentListener
5091      * @since 1.4
5092      */
5093     public synchronized ComponentListener[] getComponentListeners() {
5094         return (ComponentListener[]) (getListeners(ComponentListener.class));
5095     }
5096 
5097     /**
5098      * Adds the specified focus listener to receive focus events from
5099      * this component when this component gains input focus.
5100      * If listener <code>l</code> is <code>null</code>,
5101      * no exception is thrown and no action is performed.
5102      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5103      * >AWT Threading Issues</a> for details on AWT's threading model.
5104      *
5105      * @param    l   the focus listener
5106      * @see      java.awt.event.FocusEvent
5107      * @see      java.awt.event.FocusListener
5108      * @see      #removeFocusListener
5109      * @see      #getFocusListeners
5110      * @since    JDK1.1
5111      */
5112     public synchronized void addFocusListener(FocusListener l) {
5113         if (l == null) {
5114             return;
5115         }
5116         focusListener = AWTEventMulticaster.add(focusListener, l);
5117         newEventsOnly = true;
5118 
5119         // if this is a lightweight component, enable focus events
5120         // in the native container.
5121         if (peer instanceof LightweightPeer) {
5122             parent.proxyEnableEvents(AWTEvent.FOCUS_EVENT_MASK);
5123         }
5124     }
5125 
5126     /**
5127      * Removes the specified focus listener so that it no longer
5128      * receives focus events from this component. This method performs
5129      * no function, nor does it throw an exception, if the listener
5130      * specified by the argument was not previously added to this component.
5131      * If listener <code>l</code> is <code>null</code>,
5132      * no exception is thrown and no action is performed.
5133      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5134      * >AWT Threading Issues</a> for details on AWT's threading model.
5135      *
5136      * @param    l   the focus listener
5137      * @see      java.awt.event.FocusEvent
5138      * @see      java.awt.event.FocusListener
5139      * @see      #addFocusListener
5140      * @see      #getFocusListeners
5141      * @since    JDK1.1
5142      */
5143     public synchronized void removeFocusListener(FocusListener l) {
5144         if (l == null) {
5145             return;
5146         }
5147         focusListener = AWTEventMulticaster.remove(focusListener, l);
5148     }
5149 
5150     /**
5151      * Returns an array of all the focus listeners
5152      * registered on this component.
5153      *
5154      * @return all of this component's <code>FocusListener</code>s
5155      *         or an empty array if no component
5156      *         listeners are currently registered
5157      *
5158      * @see #addFocusListener
5159      * @see #removeFocusListener
5160      * @since 1.4
5161      */
5162     public synchronized FocusListener[] getFocusListeners() {
5163         return (FocusListener[]) (getListeners(FocusListener.class));
5164     }
5165 
5166     /**
5167      * Adds the specified hierarchy listener to receive hierarchy changed
5168      * events from this component when the hierarchy to which this container
5169      * belongs changes.
5170      * If listener <code>l</code> is <code>null</code>,
5171      * no exception is thrown and no action is performed.
5172      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5173      * >AWT Threading Issues</a> for details on AWT's threading model.
5174      *
5175      * @param    l   the hierarchy listener
5176      * @see      java.awt.event.HierarchyEvent
5177      * @see      java.awt.event.HierarchyListener
5178      * @see      #removeHierarchyListener
5179      * @see      #getHierarchyListeners
5180      * @since    1.3
5181      */
5182     public void addHierarchyListener(HierarchyListener l) {
5183         if (l == null) {
5184             return;
5185         }
5186         boolean notifyAncestors;
5187         synchronized (this) {
5188             notifyAncestors =
5189                 (hierarchyListener == null &&
5190                  (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0);
5191             hierarchyListener = AWTEventMulticaster.add(hierarchyListener, l);
5192             notifyAncestors = (notifyAncestors && hierarchyListener != null);
5193             newEventsOnly = true;
5194         }
5195         if (notifyAncestors) {
5196             synchronized (getTreeLock()) {
5197                 adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK,
5198                                                 1);
5199             }
5200         }
5201     }
5202 
5203     /**
5204      * Removes the specified hierarchy listener so that it no longer
5205      * receives hierarchy changed events from this component. This method
5206      * performs no function, nor does it throw an exception, if the listener
5207      * specified by the argument was not previously added to this component.
5208      * If listener <code>l</code> is <code>null</code>,
5209      * no exception is thrown and no action is performed.
5210      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5211      * >AWT Threading Issues</a> for details on AWT's threading model.
5212      *
5213      * @param    l   the hierarchy listener
5214      * @see      java.awt.event.HierarchyEvent
5215      * @see      java.awt.event.HierarchyListener
5216      * @see      #addHierarchyListener
5217      * @see      #getHierarchyListeners
5218      * @since    1.3
5219      */
5220     public void removeHierarchyListener(HierarchyListener l) {
5221         if (l == null) {
5222             return;
5223         }
5224         boolean notifyAncestors;
5225         synchronized (this) {
5226             notifyAncestors =
5227                 (hierarchyListener != null &&
5228                  (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0);
5229             hierarchyListener =
5230                 AWTEventMulticaster.remove(hierarchyListener, l);
5231             notifyAncestors = (notifyAncestors && hierarchyListener == null);
5232         }
5233         if (notifyAncestors) {
5234             synchronized (getTreeLock()) {
5235                 adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK,
5236                                                 -1);
5237             }
5238         }
5239     }
5240 
5241     /**
5242      * Returns an array of all the hierarchy listeners
5243      * registered on this component.
5244      *
5245      * @return all of this component's <code>HierarchyListener</code>s
5246      *         or an empty array if no hierarchy
5247      *         listeners are currently registered
5248      *
5249      * @see      #addHierarchyListener
5250      * @see      #removeHierarchyListener
5251      * @since    1.4
5252      */
5253     public synchronized HierarchyListener[] getHierarchyListeners() {
5254         return (HierarchyListener[])(getListeners(HierarchyListener.class));
5255     }
5256 
5257     /**
5258      * Adds the specified hierarchy bounds listener to receive hierarchy
5259      * bounds events from this component when the hierarchy to which this
5260      * container belongs changes.
5261      * If listener <code>l</code> is <code>null</code>,
5262      * no exception is thrown and no action is performed.
5263      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5264      * >AWT Threading Issues</a> for details on AWT's threading model.
5265      *
5266      * @param    l   the hierarchy bounds listener
5267      * @see      java.awt.event.HierarchyEvent
5268      * @see      java.awt.event.HierarchyBoundsListener
5269      * @see      #removeHierarchyBoundsListener
5270      * @see      #getHierarchyBoundsListeners
5271      * @since    1.3
5272      */
5273     public void addHierarchyBoundsListener(HierarchyBoundsListener l) {
5274         if (l == null) {
5275             return;
5276         }
5277         boolean notifyAncestors;
5278         synchronized (this) {
5279             notifyAncestors =
5280                 (hierarchyBoundsListener == null &&
5281                  (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0);
5282             hierarchyBoundsListener =
5283                 AWTEventMulticaster.add(hierarchyBoundsListener, l);
5284             notifyAncestors = (notifyAncestors &&
5285                                hierarchyBoundsListener != null);
5286             newEventsOnly = true;
5287         }
5288         if (notifyAncestors) {
5289             synchronized (getTreeLock()) {
5290                 adjustListeningChildrenOnParent(
5291                                                 AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, 1);
5292             }
5293         }
5294     }
5295 
5296     /**
5297      * Removes the specified hierarchy bounds listener so that it no longer
5298      * receives hierarchy bounds events from this component. This method
5299      * performs no function, nor does it throw an exception, if the listener
5300      * specified by the argument was not previously added to this component.
5301      * If listener <code>l</code> is <code>null</code>,
5302      * no exception is thrown and no action is performed.
5303      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5304      * >AWT Threading Issues</a> for details on AWT's threading model.
5305      *
5306      * @param    l   the hierarchy bounds listener
5307      * @see      java.awt.event.HierarchyEvent
5308      * @see      java.awt.event.HierarchyBoundsListener
5309      * @see      #addHierarchyBoundsListener
5310      * @see      #getHierarchyBoundsListeners
5311      * @since    1.3
5312      */
5313     public void removeHierarchyBoundsListener(HierarchyBoundsListener l) {
5314         if (l == null) {
5315             return;
5316         }
5317         boolean notifyAncestors;
5318         synchronized (this) {
5319             notifyAncestors =
5320                 (hierarchyBoundsListener != null &&
5321                  (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0);
5322             hierarchyBoundsListener =
5323                 AWTEventMulticaster.remove(hierarchyBoundsListener, l);
5324             notifyAncestors = (notifyAncestors &&
5325                                hierarchyBoundsListener == null);
5326         }
5327         if (notifyAncestors) {
5328             synchronized (getTreeLock()) {
5329                 adjustListeningChildrenOnParent(
5330                                                 AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, -1);
5331             }
5332         }
5333     }
5334 
5335     // Should only be called while holding the tree lock
5336     int numListening(long mask) {
5337         // One mask or the other, but not neither or both.
5338         if (eventLog.isLoggable(Level.FINE)) {
5339             if ((mask != AWTEvent.HIERARCHY_EVENT_MASK) &&
5340                 (mask != AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK))
5341             {
5342                 eventLog.log(Level.FINE, "Assertion failed");
5343             }
5344         }
5345         if ((mask == AWTEvent.HIERARCHY_EVENT_MASK &&
5346              (hierarchyListener != null ||
5347               (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0)) ||
5348             (mask == AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK &&
5349              (hierarchyBoundsListener != null ||
5350               (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0))) {
5351             return 1;
5352         } else {
5353             return 0;
5354         }
5355     }
5356 
5357     // Should only be called while holding tree lock
5358     int countHierarchyMembers() {
5359         return 1;
5360     }
5361     // Should only be called while holding the tree lock
5362     int createHierarchyEvents(int id, Component changed,
5363                               Container changedParent, long changeFlags,
5364                               boolean enabledOnToolkit) {
5365         switch (id) {
5366           case HierarchyEvent.HIERARCHY_CHANGED:
5367               if (hierarchyListener != null ||
5368                   (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
5369                   enabledOnToolkit) {
5370                   HierarchyEvent e = new HierarchyEvent(this, id, changed,
5371                                                         changedParent,
5372                                                         changeFlags);
5373                   dispatchEvent(e);
5374                   return 1;
5375               }
5376               break;
5377           case HierarchyEvent.ANCESTOR_MOVED:
5378           case HierarchyEvent.ANCESTOR_RESIZED:
5379               if (eventLog.isLoggable(Level.FINE)) {
5380                   if (changeFlags != 0) {
5381                       eventLog.log(Level.FINE, "Assertion (changeFlags == 0) failed");
5382                   }
5383               }
5384               if (hierarchyBoundsListener != null ||
5385                   (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 ||
5386                   enabledOnToolkit) {
5387                   HierarchyEvent e = new HierarchyEvent(this, id, changed,
5388                                                         changedParent);
5389                   dispatchEvent(e);
5390                   return 1;
5391               }
5392               break;
5393           default:
5394               // assert false
5395               if (eventLog.isLoggable(Level.FINE)) {
5396                   eventLog.log(Level.FINE, "This code must never be reached");
5397               }
5398               break;
5399         }
5400         return 0;
5401     }
5402 
5403     /**
5404      * Returns an array of all the hierarchy bounds listeners
5405      * registered on this component.
5406      *
5407      * @return all of this component's <code>HierarchyBoundsListener</code>s
5408      *         or an empty array if no hierarchy bounds
5409      *         listeners are currently registered
5410      *
5411      * @see      #addHierarchyBoundsListener
5412      * @see      #removeHierarchyBoundsListener
5413      * @since    1.4
5414      */
5415     public synchronized HierarchyBoundsListener[] getHierarchyBoundsListeners() {
5416         return (HierarchyBoundsListener[])
5417             (getListeners(HierarchyBoundsListener.class));
5418     }
5419 
5420     /*
5421      * Should only be called while holding the tree lock.
5422      * It's added only for overriding in java.awt.Window
5423      * because parent in Window is owner.
5424      */
5425     void adjustListeningChildrenOnParent(long mask, int num) {
5426         if (parent != null) {
5427             parent.adjustListeningChildren(mask, num);
5428         }
5429     }
5430 
5431     /**
5432      * Adds the specified key listener to receive key events from
5433      * this component.
5434      * If l is null, no exception is thrown and no action is performed.
5435      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5436      * >AWT Threading Issues</a> for details on AWT's threading model.
5437      *
5438      * @param    l   the key listener.
5439      * @see      java.awt.event.KeyEvent
5440      * @see      java.awt.event.KeyListener
5441      * @see      #removeKeyListener
5442      * @see      #getKeyListeners
5443      * @since    JDK1.1
5444      */
5445     public synchronized void addKeyListener(KeyListener l) {
5446         if (l == null) {
5447             return;
5448         }
5449         keyListener = AWTEventMulticaster.add(keyListener, l);
5450         newEventsOnly = true;
5451 
5452         // if this is a lightweight component, enable key events
5453         // in the native container.
5454         if (peer instanceof LightweightPeer) {
5455             parent.proxyEnableEvents(AWTEvent.KEY_EVENT_MASK);
5456         }
5457     }
5458 
5459     /**
5460      * Removes the specified key listener so that it no longer
5461      * receives key events from this component. This method performs
5462      * no function, nor does it throw an exception, if the listener
5463      * specified by the argument was not previously added to this component.
5464      * If listener <code>l</code> is <code>null</code>,
5465      * no exception is thrown and no action is performed.
5466      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5467      * >AWT Threading Issues</a> for details on AWT's threading model.
5468      *
5469      * @param    l   the key listener
5470      * @see      java.awt.event.KeyEvent
5471      * @see      java.awt.event.KeyListener
5472      * @see      #addKeyListener
5473      * @see      #getKeyListeners
5474      * @since    JDK1.1
5475      */
5476     public synchronized void removeKeyListener(KeyListener l) {
5477         if (l == null) {
5478             return;
5479         }
5480         keyListener = AWTEventMulticaster.remove(keyListener, l);
5481     }
5482 
5483     /**
5484      * Returns an array of all the key listeners
5485      * registered on this component.
5486      *
5487      * @return all of this component's <code>KeyListener</code>s
5488      *         or an empty array if no key
5489      *         listeners are currently registered
5490      *
5491      * @see      #addKeyListener
5492      * @see      #removeKeyListener
5493      * @since    1.4
5494      */
5495     public synchronized KeyListener[] getKeyListeners() {
5496         return (KeyListener[]) (getListeners(KeyListener.class));
5497     }
5498 
5499     /**
5500      * Adds the specified mouse listener to receive mouse events from
5501      * this component.
5502      * If listener <code>l</code> is <code>null</code>,
5503      * no exception is thrown and no action is performed.
5504      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5505      * >AWT Threading Issues</a> for details on AWT's threading model.
5506      *
5507      * @param    l   the mouse listener
5508      * @see      java.awt.event.MouseEvent
5509      * @see      java.awt.event.MouseListener
5510      * @see      #removeMouseListener
5511      * @see      #getMouseListeners
5512      * @since    JDK1.1
5513      */
5514     public synchronized void addMouseListener(MouseListener l) {
5515         if (l == null) {
5516             return;
5517         }
5518         mouseListener = AWTEventMulticaster.add(mouseListener,l);
5519         newEventsOnly = true;
5520 
5521         // if this is a lightweight component, enable mouse events
5522         // in the native container.
5523         if (peer instanceof LightweightPeer) {
5524             parent.proxyEnableEvents(AWTEvent.MOUSE_EVENT_MASK);
5525         }
5526     }
5527 
5528     /**
5529      * Removes the specified mouse listener so that it no longer
5530      * receives mouse events from this component. This method performs
5531      * no function, nor does it throw an exception, if the listener
5532      * specified by the argument was not previously added to this component.
5533      * If listener <code>l</code> is <code>null</code>,
5534      * no exception is thrown and no action is performed.
5535      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5536      * >AWT Threading Issues</a> for details on AWT's threading model.
5537      *
5538      * @param    l   the mouse listener
5539      * @see      java.awt.event.MouseEvent
5540      * @see      java.awt.event.MouseListener
5541      * @see      #addMouseListener
5542      * @see      #getMouseListeners
5543      * @since    JDK1.1
5544      */
5545     public synchronized void removeMouseListener(MouseListener l) {
5546         if (l == null) {
5547             return;
5548         }
5549         mouseListener = AWTEventMulticaster.remove(mouseListener, l);
5550     }
5551 
5552     /**
5553      * Returns an array of all the mouse listeners
5554      * registered on this component.
5555      *
5556      * @return all of this component's <code>MouseListener</code>s
5557      *         or an empty array if no mouse
5558      *         listeners are currently registered
5559      *
5560      * @see      #addMouseListener
5561      * @see      #removeMouseListener
5562      * @since    1.4
5563      */
5564     public synchronized MouseListener[] getMouseListeners() {
5565         return (MouseListener[]) (getListeners(MouseListener.class));
5566     }
5567 
5568     /**
5569      * Adds the specified mouse motion listener to receive mouse motion
5570      * events from this component.
5571      * If listener <code>l</code> is <code>null</code>,
5572      * no exception is thrown and no action is performed.
5573      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5574      * >AWT Threading Issues</a> for details on AWT's threading model.
5575      *
5576      * @param    l   the mouse motion listener
5577      * @see      java.awt.event.MouseEvent
5578      * @see      java.awt.event.MouseMotionListener
5579      * @see      #removeMouseMotionListener
5580      * @see      #getMouseMotionListeners
5581      * @since    JDK1.1
5582      */
5583     public synchronized void addMouseMotionListener(MouseMotionListener l) {
5584         if (l == null) {
5585             return;
5586         }
5587         mouseMotionListener = AWTEventMulticaster.add(mouseMotionListener,l);
5588         newEventsOnly = true;
5589 
5590         // if this is a lightweight component, enable mouse events
5591         // in the native container.
5592         if (peer instanceof LightweightPeer) {
5593             parent.proxyEnableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
5594         }
5595     }
5596 
5597     /**
5598      * Removes the specified mouse motion listener so that it no longer
5599      * receives mouse motion events from this component. This method performs
5600      * no function, nor does it throw an exception, if the listener
5601      * specified by the argument was not previously added to this component.
5602      * If listener <code>l</code> is <code>null</code>,
5603      * no exception is thrown and no action is performed.
5604      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5605      * >AWT Threading Issues</a> for details on AWT's threading model.
5606      *
5607      * @param    l   the mouse motion listener
5608      * @see      java.awt.event.MouseEvent
5609      * @see      java.awt.event.MouseMotionListener
5610      * @see      #addMouseMotionListener
5611      * @see      #getMouseMotionListeners
5612      * @since    JDK1.1
5613      */
5614     public synchronized void removeMouseMotionListener(MouseMotionListener l) {
5615         if (l == null) {
5616             return;
5617         }
5618         mouseMotionListener = AWTEventMulticaster.remove(mouseMotionListener, l);
5619     }
5620 
5621     /**
5622      * Returns an array of all the mouse motion listeners
5623      * registered on this component.
5624      *
5625      * @return all of this component's <code>MouseMotionListener</code>s
5626      *         or an empty array if no mouse motion
5627      *         listeners are currently registered
5628      *
5629      * @see      #addMouseMotionListener
5630      * @see      #removeMouseMotionListener
5631      * @since    1.4
5632      */
5633     public synchronized MouseMotionListener[] getMouseMotionListeners() {
5634         return (MouseMotionListener[]) (getListeners(MouseMotionListener.class));
5635     }
5636 
5637     /**
5638      * Adds the specified mouse wheel listener to receive mouse wheel events
5639      * from this component.  Containers also receive mouse wheel events from
5640      * sub-components.
5641      * <p>
5642      * For information on how mouse wheel events are dispatched, see
5643      * the class description for {@link MouseWheelEvent}.
5644      * <p>
5645      * If l is <code>null</code>, no exception is thrown and no
5646      * action is performed.
5647      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5648      * >AWT Threading Issues</a> for details on AWT's threading model.
5649      *
5650      * @param    l   the mouse wheel listener
5651      * @see      java.awt.event.MouseWheelEvent
5652      * @see      java.awt.event.MouseWheelListener
5653      * @see      #removeMouseWheelListener
5654      * @see      #getMouseWheelListeners
5655      * @since    1.4
5656      */
5657     public synchronized void addMouseWheelListener(MouseWheelListener l) {
5658         if (l == null) {
5659             return;
5660         }
5661         mouseWheelListener = AWTEventMulticaster.add(mouseWheelListener,l);
5662         newEventsOnly = true;
5663 
5664         // if this is a lightweight component, enable mouse events
5665         // in the native container.
5666         if (peer instanceof LightweightPeer) {
5667             parent.proxyEnableEvents(AWTEvent.MOUSE_WHEEL_EVENT_MASK);
5668         }
5669     }
5670 
5671     /**
5672      * Removes the specified mouse wheel listener so that it no longer
5673      * receives mouse wheel events from this component. This method performs
5674      * no function, nor does it throw an exception, if the listener
5675      * specified by the argument was not previously added to this component.
5676      * If l is null, no exception is thrown and no action is performed.
5677      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5678      * >AWT Threading Issues</a> for details on AWT's threading model.
5679      *
5680      * @param    l   the mouse wheel listener.
5681      * @see      java.awt.event.MouseWheelEvent
5682      * @see      java.awt.event.MouseWheelListener
5683      * @see      #addMouseWheelListener
5684      * @see      #getMouseWheelListeners
5685      * @since    1.4
5686      */
5687     public synchronized void removeMouseWheelListener(MouseWheelListener l) {
5688         if (l == null) {
5689             return;
5690         }
5691         mouseWheelListener = AWTEventMulticaster.remove(mouseWheelListener, l);
5692     }
5693 
5694     /**
5695      * Returns an array of all the mouse wheel listeners
5696      * registered on this component.
5697      *
5698      * @return all of this component's <code>MouseWheelListener</code>s
5699      *         or an empty array if no mouse wheel
5700      *         listeners are currently registered
5701      *
5702      * @see      #addMouseWheelListener
5703      * @see      #removeMouseWheelListener
5704      * @since    1.4
5705      */
5706     public synchronized MouseWheelListener[] getMouseWheelListeners() {
5707         return (MouseWheelListener[]) (getListeners(MouseWheelListener.class));
5708     }
5709 
5710     /**
5711      * Adds the specified input method listener to receive
5712      * input method events from this component. A component will
5713      * only receive input method events from input methods
5714      * if it also overrides <code>getInputMethodRequests</code> to return an
5715      * <code>InputMethodRequests</code> instance.
5716      * If listener <code>l</code> is <code>null</code>,
5717      * no exception is thrown and no action is performed.
5718      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5719      * >AWT Threading Issues</a> for details on AWT's threading model.
5720      *
5721      * @param    l   the input method listener
5722      * @see      java.awt.event.InputMethodEvent
5723      * @see      java.awt.event.InputMethodListener
5724      * @see      #removeInputMethodListener
5725      * @see      #getInputMethodListeners
5726      * @see      #getInputMethodRequests
5727      * @since    1.2
5728      */
5729     public synchronized void addInputMethodListener(InputMethodListener l) {
5730         if (l == null) {
5731             return;
5732         }
5733         inputMethodListener = AWTEventMulticaster.add(inputMethodListener, l);
5734         newEventsOnly = true;
5735     }
5736 
5737     /**
5738      * Removes the specified input method listener so that it no longer
5739      * receives input method events from this component. This method performs
5740      * no function, nor does it throw an exception, if the listener
5741      * specified by the argument was not previously added to this component.
5742      * If listener <code>l</code> is <code>null</code>,
5743      * no exception is thrown and no action is performed.
5744      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5745      * >AWT Threading Issues</a> for details on AWT's threading model.
5746      *
5747      * @param    l   the input method listener
5748      * @see      java.awt.event.InputMethodEvent
5749      * @see      java.awt.event.InputMethodListener
5750      * @see      #addInputMethodListener
5751      * @see      #getInputMethodListeners
5752      * @since    1.2
5753      */
5754     public synchronized void removeInputMethodListener(InputMethodListener l) {
5755         if (l == null) {
5756             return;
5757         }
5758         inputMethodListener = AWTEventMulticaster.remove(inputMethodListener, l);
5759     }
5760 
5761     /**
5762      * Returns an array of all the input method listeners
5763      * registered on this component.
5764      *
5765      * @return all of this component's <code>InputMethodListener</code>s
5766      *         or an empty array if no input method
5767      *         listeners are currently registered
5768      *
5769      * @see      #addInputMethodListener
5770      * @see      #removeInputMethodListener
5771      * @since    1.4
5772      */
5773     public synchronized InputMethodListener[] getInputMethodListeners() {
5774         return (InputMethodListener[]) (getListeners(InputMethodListener.class));
5775     }
5776 
5777     /**
5778      * Returns an array of all the objects currently registered
5779      * as <code><em>Foo</em>Listener</code>s
5780      * upon this <code>Component</code>.
5781      * <code><em>Foo</em>Listener</code>s are registered using the
5782      * <code>add<em>Foo</em>Listener</code> method.
5783      *
5784      * <p>
5785      * You can specify the <code>listenerType</code> argument
5786      * with a class literal, such as
5787      * <code><em>Foo</em>Listener.class</code>.
5788      * For example, you can query a
5789      * <code>Component</code> <code>c</code>
5790      * for its mouse listeners with the following code:
5791      *
5792      * <pre>MouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class));</pre>
5793      *
5794      * If no such listeners exist, this method returns an empty array.
5795      *
5796      * @param listenerType the type of listeners requested; this parameter
5797      *          should specify an interface that descends from
5798      *          <code>java.util.EventListener</code>
5799      * @return an array of all objects registered as
5800      *          <code><em>Foo</em>Listener</code>s on this component,
5801      *          or an empty array if no such listeners have been added
5802      * @exception ClassCastException if <code>listenerType</code>
5803      *          doesn't specify a class or interface that implements
5804      *          <code>java.util.EventListener</code>
5805      *
5806      * @see #getComponentListeners
5807      * @see #getFocusListeners
5808      * @see #getHierarchyListeners
5809      * @see #getHierarchyBoundsListeners
5810      * @see #getKeyListeners
5811      * @see #getMouseListeners
5812      * @see #getMouseMotionListeners
5813      * @see #getMouseWheelListeners
5814      * @see #getInputMethodListeners
5815      * @see #getPropertyChangeListeners
5816      *
5817      * @since 1.3
5818      */
5819     public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
5820         EventListener l = null;
5821         if  (listenerType == ComponentListener.class) {
5822             l = componentListener;
5823         } else if (listenerType == FocusListener.class) {
5824             l = focusListener;
5825         } else if (listenerType == HierarchyListener.class) {
5826             l = hierarchyListener;
5827         } else if (listenerType == HierarchyBoundsListener.class) {
5828             l = hierarchyBoundsListener;
5829         } else if (listenerType == KeyListener.class) {
5830             l = keyListener;
5831         } else if (listenerType == MouseListener.class) {
5832             l = mouseListener;
5833         } else if (listenerType == MouseMotionListener.class) {
5834             l = mouseMotionListener;
5835         } else if (listenerType == MouseWheelListener.class) {
5836             l = mouseWheelListener;
5837         } else if (listenerType == InputMethodListener.class) {
5838             l = inputMethodListener;
5839         } else if (listenerType == PropertyChangeListener.class) {
5840             return (T[])getPropertyChangeListeners();
5841         }
5842         return AWTEventMulticaster.getListeners(l, listenerType);
5843     }
5844 
5845     /**
5846      * Gets the input method request handler which supports
5847      * requests from input methods for this component. A component
5848      * that supports on-the-spot text input must override this
5849      * method to return an <code>InputMethodRequests</code> instance.
5850      * At the same time, it also has to handle input method events.
5851      *
5852      * @return the input method request handler for this component,
5853      *          <code>null</code> by default
5854      * @see #addInputMethodListener
5855      * @since 1.2
5856      */
5857     public InputMethodRequests getInputMethodRequests() {
5858         return null;
5859     }
5860 
5861     /**
5862      * Gets the input context used by this component for handling
5863      * the communication with input methods when text is entered
5864      * in this component. By default, the input context used for
5865      * the parent component is returned. Components may
5866      * override this to return a private input context.
5867      *
5868      * @return the input context used by this component;
5869      *          <code>null</code> if no context can be determined
5870      * @since 1.2
5871      */
5872     public InputContext getInputContext() {
5873         Container parent = this.parent;
5874         if (parent == null) {
5875             return null;
5876         } else {
5877             return parent.getInputContext();
5878         }
5879     }
5880 
5881     /**
5882      * Enables the events defined by the specified event mask parameter
5883      * to be delivered to this component.
5884      * <p>
5885      * Event types are automatically enabled when a listener for
5886      * that event type is added to the component.
5887      * <p>
5888      * This method only needs to be invoked by subclasses of
5889      * <code>Component</code> which desire to have the specified event
5890      * types delivered to <code>processEvent</code> regardless of whether
5891      * or not a listener is registered.
5892      * @param      eventsToEnable   the event mask defining the event types
5893      * @see        #processEvent
5894      * @see        #disableEvents
5895      * @see        AWTEvent
5896      * @since      JDK1.1
5897      */
5898     protected final void enableEvents(long eventsToEnable) {
5899         long notifyAncestors = 0;
5900         synchronized (this) {
5901             if ((eventsToEnable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 &&
5902                 hierarchyListener == null &&
5903                 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0) {
5904                 notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK;
5905             }
5906             if ((eventsToEnable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 &&
5907                 hierarchyBoundsListener == null &&
5908                 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0) {
5909                 notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK;
5910             }
5911             eventMask |= eventsToEnable;
5912             newEventsOnly = true;
5913         }
5914 
5915         // if this is a lightweight component, enable mouse events
5916         // in the native container.
5917         if (peer instanceof LightweightPeer) {
5918             parent.proxyEnableEvents(eventMask);
5919         }
5920         if (notifyAncestors != 0) {
5921             synchronized (getTreeLock()) {
5922                 adjustListeningChildrenOnParent(notifyAncestors, 1);
5923             }
5924         }
5925     }
5926 
5927     /**
5928      * Disables the events defined by the specified event mask parameter
5929      * from being delivered to this component.
5930      * @param      eventsToDisable   the event mask defining the event types
5931      * @see        #enableEvents
5932      * @since      JDK1.1
5933      */
5934     protected final void disableEvents(long eventsToDisable) {
5935         long notifyAncestors = 0;
5936         synchronized (this) {
5937             if ((eventsToDisable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 &&
5938                 hierarchyListener == null &&
5939                 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0) {
5940                 notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK;
5941             }
5942             if ((eventsToDisable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK)!=0 &&
5943                 hierarchyBoundsListener == null &&
5944                 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0) {
5945                 notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK;
5946             }
5947             eventMask &= ~eventsToDisable;
5948         }
5949         if (notifyAncestors != 0) {
5950             synchronized (getTreeLock()) {
5951                 adjustListeningChildrenOnParent(notifyAncestors, -1);
5952             }
5953         }
5954     }
5955 
5956     transient sun.awt.EventQueueItem[] eventCache;
5957 
5958     /**
5959      * @see #isCoalescingEnabled
5960      * @see #checkCoalescing
5961      */
5962     transient private boolean coalescingEnabled = checkCoalescing();
5963 
5964     /**
5965      * Weak map of known coalesceEvent overriders.
5966      * Value indicates whether overriden.
5967      * Bootstrap classes are not included.
5968      */
5969     private static final Map<Class<?>, Boolean> coalesceMap =
5970         new java.util.WeakHashMap<Class<?>, Boolean>();
5971 
5972     /**
5973      * Indicates whether this class overrides coalesceEvents.
5974      * It is assumed that all classes that are loaded from the bootstrap
5975      *   do not.
5976      * The boostrap class loader is assumed to be represented by null.
5977      * We do not check that the method really overrides
5978      *   (it might be static, private or package private).
5979      */
5980      private boolean checkCoalescing() {
5981          if (getClass().getClassLoader()==null) {
5982              return false;
5983          }
5984          final Class<? extends Component> clazz = getClass();
5985          synchronized (coalesceMap) {
5986              // Check cache.
5987              Boolean value = coalesceMap.get(clazz);
5988              if (value != null) {
5989                  return value;
5990              }
5991 
5992              // Need to check non-bootstraps.
5993              Boolean enabled = java.security.AccessController.doPrivileged(
5994                  new java.security.PrivilegedAction<Boolean>() {
5995                      public Boolean run() {
5996                          return isCoalesceEventsOverriden(clazz);
5997                      }
5998                  }
5999                  );
6000              coalesceMap.put(clazz, enabled);
6001              return enabled;
6002          }
6003      }
6004 
6005     /**
6006      * Parameter types of coalesceEvents(AWTEvent,AWTEVent).
6007      */
6008     private static final Class[] coalesceEventsParams = {
6009         AWTEvent.class, AWTEvent.class
6010     };
6011 
6012     /**
6013      * Indicates whether a class or its superclasses override coalesceEvents.
6014      * Must be called with lock on coalesceMap and privileged.
6015      * @see checkCoalsecing
6016      */
6017     private static boolean isCoalesceEventsOverriden(Class<?> clazz) {
6018         assert Thread.holdsLock(coalesceMap);
6019 
6020         // First check superclass - we may not need to bother ourselves.
6021         Class<?> superclass = clazz.getSuperclass();
6022         if (superclass == null) {
6023             // Only occurs on implementations that
6024             //   do not use null to represent the bootsrap class loader.
6025             return false;
6026         }
6027         if (superclass.getClassLoader() != null) {
6028             Boolean value = coalesceMap.get(superclass);
6029             if (value == null) {
6030                 // Not done already - recurse.
6031                 if (isCoalesceEventsOverriden(superclass)) {
6032                     coalesceMap.put(superclass, true);
6033                     return true;
6034                 }
6035             } else if (value) {
6036                 return true;
6037             }
6038         }
6039 
6040         try {
6041             // Throws if not overriden.
6042             clazz.getDeclaredMethod(
6043                 "coalesceEvents", coalesceEventsParams
6044                 );
6045             return true;
6046         } catch (NoSuchMethodException e) {
6047             // Not present in this class.
6048             return false;
6049         }
6050     }
6051 
6052     /**
6053      * Indicates whether coalesceEvents may do something.
6054      */
6055     final boolean isCoalescingEnabled() {
6056         return coalescingEnabled;
6057      }
6058 
6059 
6060     /**
6061      * Potentially coalesce an event being posted with an existing
6062      * event.  This method is called by <code>EventQueue.postEvent</code>
6063      * if an event with the same ID as the event to be posted is found in
6064      * the queue (both events must have this component as their source).
6065      * This method either returns a coalesced event which replaces
6066      * the existing event (and the new event is then discarded), or
6067      * <code>null</code> to indicate that no combining should be done
6068      * (add the second event to the end of the queue).  Either event
6069      * parameter may be modified and returned, as the other one is discarded
6070      * unless <code>null</code> is returned.
6071      * <p>
6072      * This implementation of <code>coalesceEvents</code> coalesces
6073      * two event types: mouse move (and drag) events,
6074      * and paint (and update) events.
6075      * For mouse move events the last event is always returned, causing
6076      * intermediate moves to be discarded.  For paint events, the new
6077      * event is coalesced into a complex <code>RepaintArea</code> in the peer.
6078      * The new <code>AWTEvent</code> is always returned.
6079      *
6080      * @param  existingEvent  the event already on the <code>EventQueue</code>
6081      * @param  newEvent       the event being posted to the
6082      *          <code>EventQueue</code>
6083      * @return a coalesced event, or <code>null</code> indicating that no
6084      *          coalescing was done
6085      */
6086     protected AWTEvent coalesceEvents(AWTEvent existingEvent,
6087                                       AWTEvent newEvent) {
6088         return null;
6089     }
6090 
6091     /**
6092      * Processes events occurring on this component. By default this
6093      * method calls the appropriate
6094      * <code>process&lt;event&nbsp;type&gt;Event</code>
6095      * method for the given class of event.
6096      * <p>Note that if the event parameter is <code>null</code>
6097      * the behavior is unspecified and may result in an
6098      * exception.
6099      *
6100      * @param     e the event
6101      * @see       #processComponentEvent
6102      * @see       #processFocusEvent
6103      * @see       #processKeyEvent
6104      * @see       #processMouseEvent
6105      * @see       #processMouseMotionEvent
6106      * @see       #processInputMethodEvent
6107      * @see       #processHierarchyEvent
6108      * @see       #processMouseWheelEvent
6109      * @since     JDK1.1
6110      */
6111     protected void processEvent(AWTEvent e) {
6112         if (e instanceof FocusEvent) {
6113             processFocusEvent((FocusEvent)e);
6114 
6115         } else if (e instanceof MouseEvent) {
6116             switch(e.getID()) {
6117               case MouseEvent.MOUSE_PRESSED:
6118               case MouseEvent.MOUSE_RELEASED:
6119               case MouseEvent.MOUSE_CLICKED:
6120               case MouseEvent.MOUSE_ENTERED:
6121               case MouseEvent.MOUSE_EXITED:
6122                   processMouseEvent((MouseEvent)e);
6123                   break;
6124               case MouseEvent.MOUSE_MOVED:
6125               case MouseEvent.MOUSE_DRAGGED:
6126                   processMouseMotionEvent((MouseEvent)e);
6127                   break;
6128               case MouseEvent.MOUSE_WHEEL:
6129                   processMouseWheelEvent((MouseWheelEvent)e);
6130                   break;
6131             }
6132 
6133         } else if (e instanceof KeyEvent) {
6134             processKeyEvent((KeyEvent)e);
6135 
6136         } else if (e instanceof ComponentEvent) {
6137             processComponentEvent((ComponentEvent)e);
6138         } else if (e instanceof InputMethodEvent) {
6139             processInputMethodEvent((InputMethodEvent)e);
6140         } else if (e instanceof HierarchyEvent) {
6141             switch (e.getID()) {
6142               case HierarchyEvent.HIERARCHY_CHANGED:
6143                   processHierarchyEvent((HierarchyEvent)e);
6144                   break;
6145               case HierarchyEvent.ANCESTOR_MOVED:
6146               case HierarchyEvent.ANCESTOR_RESIZED:
6147                   processHierarchyBoundsEvent((HierarchyEvent)e);
6148                   break;
6149             }
6150         }
6151     }
6152 
6153     /**
6154      * Processes component events occurring on this component by
6155      * dispatching them to any registered
6156      * <code>ComponentListener</code> objects.
6157      * <p>
6158      * This method is not called unless component events are
6159      * enabled for this component. Component events are enabled
6160      * when one of the following occurs:
6161      * <p><ul>
6162      * <li>A <code>ComponentListener</code> object is registered
6163      * via <code>addComponentListener</code>.
6164      * <li>Component events are enabled via <code>enableEvents</code>.
6165      * </ul>
6166      * <p>Note that if the event parameter is <code>null</code>
6167      * the behavior is unspecified and may result in an
6168      * exception.
6169      *
6170      * @param       e the component event
6171      * @see         java.awt.event.ComponentEvent
6172      * @see         java.awt.event.ComponentListener
6173      * @see         #addComponentListener
6174      * @see         #enableEvents
6175      * @since       JDK1.1
6176      */
6177     protected void processComponentEvent(ComponentEvent e) {
6178         ComponentListener listener = componentListener;
6179         if (listener != null) {
6180             int id = e.getID();
6181             switch(id) {
6182               case ComponentEvent.COMPONENT_RESIZED:
6183                   listener.componentResized(e);
6184                   break;
6185               case ComponentEvent.COMPONENT_MOVED:
6186                   listener.componentMoved(e);
6187                   break;
6188               case ComponentEvent.COMPONENT_SHOWN:
6189                   listener.componentShown(e);
6190                   break;
6191               case ComponentEvent.COMPONENT_HIDDEN:
6192                   listener.componentHidden(e);
6193                   break;
6194             }
6195         }
6196     }
6197 
6198     /**
6199      * Processes focus events occurring on this component by
6200      * dispatching them to any registered
6201      * <code>FocusListener</code> objects.
6202      * <p>
6203      * This method is not called unless focus events are
6204      * enabled for this component. Focus events are enabled
6205      * when one of the following occurs:
6206      * <p><ul>
6207      * <li>A <code>FocusListener</code> object is registered
6208      * via <code>addFocusListener</code>.
6209      * <li>Focus events are enabled via <code>enableEvents</code>.
6210      * </ul>
6211      * <p>
6212      * If focus events are enabled for a <code>Component</code>,
6213      * the current <code>KeyboardFocusManager</code> determines
6214      * whether or not a focus event should be dispatched to
6215      * registered <code>FocusListener</code> objects.  If the
6216      * events are to be dispatched, the <code>KeyboardFocusManager</code>
6217      * calls the <code>Component</code>'s <code>dispatchEvent</code>
6218      * method, which results in a call to the <code>Component</code>'s
6219      * <code>processFocusEvent</code> method.
6220      * <p>
6221      * If focus events are enabled for a <code>Component</code>, calling
6222      * the <code>Component</code>'s <code>dispatchEvent</code> method
6223      * with a <code>FocusEvent</code> as the argument will result in a
6224      * call to the <code>Component</code>'s <code>processFocusEvent</code>
6225      * method regardless of the current <code>KeyboardFocusManager</code>.
6226      * <p>
6227      * <p>Note that if the event parameter is <code>null</code>
6228      * the behavior is unspecified and may result in an
6229      * exception.
6230      *
6231      * @param       e the focus event
6232      * @see         java.awt.event.FocusEvent
6233      * @see         java.awt.event.FocusListener
6234      * @see         java.awt.KeyboardFocusManager
6235      * @see         #addFocusListener
6236      * @see         #enableEvents
6237      * @see         #dispatchEvent
6238      * @since       JDK1.1
6239      */
6240     protected void processFocusEvent(FocusEvent e) {
6241         FocusListener listener = focusListener;
6242         if (listener != null) {
6243             int id = e.getID();
6244             switch(id) {
6245               case FocusEvent.FOCUS_GAINED:
6246                   listener.focusGained(e);
6247                   break;
6248               case FocusEvent.FOCUS_LOST:
6249                   listener.focusLost(e);
6250                   break;
6251             }
6252         }
6253     }
6254 
6255     /**
6256      * Processes key events occurring on this component by
6257      * dispatching them to any registered
6258      * <code>KeyListener</code> objects.
6259      * <p>
6260      * This method is not called unless key events are
6261      * enabled for this component. Key events are enabled
6262      * when one of the following occurs:
6263      * <p><ul>
6264      * <li>A <code>KeyListener</code> object is registered
6265      * via <code>addKeyListener</code>.
6266      * <li>Key events are enabled via <code>enableEvents</code>.
6267      * </ul>
6268      *
6269      * <p>
6270      * If key events are enabled for a <code>Component</code>,
6271      * the current <code>KeyboardFocusManager</code> determines
6272      * whether or not a key event should be dispatched to
6273      * registered <code>KeyListener</code> objects.  The
6274      * <code>DefaultKeyboardFocusManager</code> will not dispatch
6275      * key events to a <code>Component</code> that is not the focus
6276      * owner or is not showing.
6277      * <p>
6278      * As of J2SE 1.4, <code>KeyEvent</code>s are redirected to
6279      * the focus owner. Please see the
6280      * <a href="doc-files/FocusSpec.html">Focus Specification</a>
6281      * for further information.
6282      * <p>
6283      * Calling a <code>Component</code>'s <code>dispatchEvent</code>
6284      * method with a <code>KeyEvent</code> as the argument will
6285      * result in a call to the <code>Component</code>'s
6286      * <code>processKeyEvent</code> method regardless of the
6287      * current <code>KeyboardFocusManager</code> as long as the
6288      * component is showing, focused, and enabled, and key events
6289      * are enabled on it.
6290      * <p>If the event parameter is <code>null</code>
6291      * the behavior is unspecified and may result in an
6292      * exception.
6293      *
6294      * @param       e the key event
6295      * @see         java.awt.event.KeyEvent
6296      * @see         java.awt.event.KeyListener
6297      * @see         java.awt.KeyboardFocusManager
6298      * @see         java.awt.DefaultKeyboardFocusManager
6299      * @see         #processEvent
6300      * @see         #dispatchEvent
6301      * @see         #addKeyListener
6302      * @see         #enableEvents
6303      * @see         #isShowing
6304      * @since       JDK1.1
6305      */
6306     protected void processKeyEvent(KeyEvent e) {
6307         KeyListener listener = keyListener;
6308         if (listener != null) {
6309             int id = e.getID();
6310             switch(id) {
6311               case KeyEvent.KEY_TYPED:
6312                   listener.keyTyped(e);
6313                   break;
6314               case KeyEvent.KEY_PRESSED:
6315                   listener.keyPressed(e);
6316                   break;
6317               case KeyEvent.KEY_RELEASED:
6318                   listener.keyReleased(e);
6319                   break;
6320             }
6321         }
6322     }
6323 
6324     /**
6325      * Processes mouse events occurring on this component by
6326      * dispatching them to any registered
6327      * <code>MouseListener</code> objects.
6328      * <p>
6329      * This method is not called unless mouse events are
6330      * enabled for this component. Mouse events are enabled
6331      * when one of the following occurs:
6332      * <p><ul>
6333      * <li>A <code>MouseListener</code> object is registered
6334      * via <code>addMouseListener</code>.
6335      * <li>Mouse events are enabled via <code>enableEvents</code>.
6336      * </ul>
6337      * <p>Note that if the event parameter is <code>null</code>
6338      * the behavior is unspecified and may result in an
6339      * exception.
6340      *
6341      * @param       e the mouse event
6342      * @see         java.awt.event.MouseEvent
6343      * @see         java.awt.event.MouseListener
6344      * @see         #addMouseListener
6345      * @see         #enableEvents
6346      * @since       JDK1.1
6347      */
6348     protected void processMouseEvent(MouseEvent e) {
6349         MouseListener listener = mouseListener;
6350         if (listener != null) {
6351             int id = e.getID();
6352             switch(id) {
6353               case MouseEvent.MOUSE_PRESSED:
6354                   listener.mousePressed(e);
6355                   break;
6356               case MouseEvent.MOUSE_RELEASED:
6357                   listener.mouseReleased(e);
6358                   break;
6359               case MouseEvent.MOUSE_CLICKED:
6360                   listener.mouseClicked(e);
6361                   break;
6362               case MouseEvent.MOUSE_EXITED:
6363                   listener.mouseExited(e);
6364                   break;
6365               case MouseEvent.MOUSE_ENTERED:
6366                   listener.mouseEntered(e);
6367                   break;
6368             }
6369         }
6370     }
6371 
6372     /**
6373      * Processes mouse motion events occurring on this component by
6374      * dispatching them to any registered
6375      * <code>MouseMotionListener</code> objects.
6376      * <p>
6377      * This method is not called unless mouse motion events are
6378      * enabled for this component. Mouse motion events are enabled
6379      * when one of the following occurs:
6380      * <p><ul>
6381      * <li>A <code>MouseMotionListener</code> object is registered
6382      * via <code>addMouseMotionListener</code>.
6383      * <li>Mouse motion events are enabled via <code>enableEvents</code>.
6384      * </ul>
6385      * <p>Note that if the event parameter is <code>null</code>
6386      * the behavior is unspecified and may result in an
6387      * exception.
6388      *
6389      * @param       e the mouse motion event
6390      * @see         java.awt.event.MouseEvent
6391      * @see         java.awt.event.MouseMotionListener
6392      * @see         #addMouseMotionListener
6393      * @see         #enableEvents
6394      * @since       JDK1.1
6395      */
6396     protected void processMouseMotionEvent(MouseEvent e) {
6397         MouseMotionListener listener = mouseMotionListener;
6398         if (listener != null) {
6399             int id = e.getID();
6400             switch(id) {
6401               case MouseEvent.MOUSE_MOVED:
6402                   listener.mouseMoved(e);
6403                   break;
6404               case MouseEvent.MOUSE_DRAGGED:
6405                   listener.mouseDragged(e);
6406                   break;
6407             }
6408         }
6409     }
6410 
6411     /**
6412      * Processes mouse wheel events occurring on this component by
6413      * dispatching them to any registered
6414      * <code>MouseWheelListener</code> objects.
6415      * <p>
6416      * This method is not called unless mouse wheel events are
6417      * enabled for this component. Mouse wheel events are enabled
6418      * when one of the following occurs:
6419      * <p><ul>
6420      * <li>A <code>MouseWheelListener</code> object is registered
6421      * via <code>addMouseWheelListener</code>.
6422      * <li>Mouse wheel events are enabled via <code>enableEvents</code>.
6423      * </ul>
6424      * <p>
6425      * For information on how mouse wheel events are dispatched, see
6426      * the class description for {@link MouseWheelEvent}.
6427      * <p>
6428      * Note that if the event parameter is <code>null</code>
6429      * the behavior is unspecified and may result in an
6430      * exception.
6431      *
6432      * @param       e the mouse wheel event
6433      * @see         java.awt.event.MouseWheelEvent
6434      * @see         java.awt.event.MouseWheelListener
6435      * @see         #addMouseWheelListener
6436      * @see         #enableEvents
6437      * @since       1.4
6438      */
6439     protected void processMouseWheelEvent(MouseWheelEvent e) {
6440         MouseWheelListener listener = mouseWheelListener;
6441         if (listener != null) {
6442             int id = e.getID();
6443             switch(id) {
6444               case MouseEvent.MOUSE_WHEEL:
6445                   listener.mouseWheelMoved(e);
6446                   break;
6447             }
6448         }
6449     }
6450 
6451     boolean postsOldMouseEvents() {
6452         return false;
6453     }
6454 
6455     /**
6456      * Processes input method events occurring on this component by
6457      * dispatching them to any registered
6458      * <code>InputMethodListener</code> objects.
6459      * <p>
6460      * This method is not called unless input method events
6461      * are enabled for this component. Input method events are enabled
6462      * when one of the following occurs:
6463      * <p><ul>
6464      * <li>An <code>InputMethodListener</code> object is registered
6465      * via <code>addInputMethodListener</code>.
6466      * <li>Input method events are enabled via <code>enableEvents</code>.
6467      * </ul>
6468      * <p>Note that if the event parameter is <code>null</code>
6469      * the behavior is unspecified and may result in an
6470      * exception.
6471      *
6472      * @param       e the input method event
6473      * @see         java.awt.event.InputMethodEvent
6474      * @see         java.awt.event.InputMethodListener
6475      * @see         #addInputMethodListener
6476      * @see         #enableEvents
6477      * @since       1.2
6478      */
6479     protected void processInputMethodEvent(InputMethodEvent e) {
6480         InputMethodListener listener = inputMethodListener;
6481         if (listener != null) {
6482             int id = e.getID();
6483             switch (id) {
6484               case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED:
6485                   listener.inputMethodTextChanged(e);
6486                   break;
6487               case InputMethodEvent.CARET_POSITION_CHANGED:
6488                   listener.caretPositionChanged(e);
6489                   break;
6490             }
6491         }
6492     }
6493 
6494     /**
6495      * Processes hierarchy events occurring on this component by
6496      * dispatching them to any registered
6497      * <code>HierarchyListener</code> objects.
6498      * <p>
6499      * This method is not called unless hierarchy events
6500      * are enabled for this component. Hierarchy events are enabled
6501      * when one of the following occurs:
6502      * <p><ul>
6503      * <li>An <code>HierarchyListener</code> object is registered
6504      * via <code>addHierarchyListener</code>.
6505      * <li>Hierarchy events are enabled via <code>enableEvents</code>.
6506      * </ul>
6507      * <p>Note that if the event parameter is <code>null</code>
6508      * the behavior is unspecified and may result in an
6509      * exception.
6510      *
6511      * @param       e the hierarchy event
6512      * @see         java.awt.event.HierarchyEvent
6513      * @see         java.awt.event.HierarchyListener
6514      * @see         #addHierarchyListener
6515      * @see         #enableEvents
6516      * @since       1.3
6517      */
6518     protected void processHierarchyEvent(HierarchyEvent e) {
6519         HierarchyListener listener = hierarchyListener;
6520         if (listener != null) {
6521             int id = e.getID();
6522             switch (id) {
6523               case HierarchyEvent.HIERARCHY_CHANGED:
6524                   listener.hierarchyChanged(e);
6525                   break;
6526             }
6527         }
6528     }
6529 
6530     /**
6531      * Processes hierarchy bounds events occurring on this component by
6532      * dispatching them to any registered
6533      * <code>HierarchyBoundsListener</code> objects.
6534      * <p>
6535      * This method is not called unless hierarchy bounds events
6536      * are enabled for this component. Hierarchy bounds events are enabled
6537      * when one of the following occurs:
6538      * <p><ul>
6539      * <li>An <code>HierarchyBoundsListener</code> object is registered
6540      * via <code>addHierarchyBoundsListener</code>.
6541      * <li>Hierarchy bounds events are enabled via <code>enableEvents</code>.
6542      * </ul>
6543      * <p>Note that if the event parameter is <code>null</code>
6544      * the behavior is unspecified and may result in an
6545      * exception.
6546      *
6547      * @param       e the hierarchy event
6548      * @see         java.awt.event.HierarchyEvent
6549      * @see         java.awt.event.HierarchyBoundsListener
6550      * @see         #addHierarchyBoundsListener
6551      * @see         #enableEvents
6552      * @since       1.3
6553      */
6554     protected void processHierarchyBoundsEvent(HierarchyEvent e) {
6555         HierarchyBoundsListener listener = hierarchyBoundsListener;
6556         if (listener != null) {
6557             int id = e.getID();
6558             switch (id) {
6559               case HierarchyEvent.ANCESTOR_MOVED:
6560                   listener.ancestorMoved(e);
6561                   break;
6562               case HierarchyEvent.ANCESTOR_RESIZED:
6563                   listener.ancestorResized(e);
6564                   break;
6565             }
6566         }
6567     }
6568 
6569     /**
6570      * @deprecated As of JDK version 1.1
6571      * replaced by processEvent(AWTEvent).
6572      */
6573     @Deprecated
6574     public boolean handleEvent(Event evt) {
6575         switch (evt.id) {
6576           case Event.MOUSE_ENTER:
6577               return mouseEnter(evt, evt.x, evt.y);
6578 
6579           case Event.MOUSE_EXIT:
6580               return mouseExit(evt, evt.x, evt.y);
6581 
6582           case Event.MOUSE_MOVE:
6583               return mouseMove(evt, evt.x, evt.y);
6584 
6585           case Event.MOUSE_DOWN:
6586               return mouseDown(evt, evt.x, evt.y);
6587 
6588           case Event.MOUSE_DRAG:
6589               return mouseDrag(evt, evt.x, evt.y);
6590 
6591           case Event.MOUSE_UP:
6592               return mouseUp(evt, evt.x, evt.y);
6593 
6594           case Event.KEY_PRESS:
6595           case Event.KEY_ACTION:
6596               return keyDown(evt, evt.key);
6597 
6598           case Event.KEY_RELEASE:
6599           case Event.KEY_ACTION_RELEASE:
6600               return keyUp(evt, evt.key);
6601 
6602           case Event.ACTION_EVENT:
6603               return action(evt, evt.arg);
6604           case Event.GOT_FOCUS:
6605               return gotFocus(evt, evt.arg);
6606           case Event.LOST_FOCUS:
6607               return lostFocus(evt, evt.arg);
6608         }
6609         return false;
6610     }
6611 
6612     /**
6613      * @deprecated As of JDK version 1.1,
6614      * replaced by processMouseEvent(MouseEvent).
6615      */
6616     @Deprecated
6617     public boolean mouseDown(Event evt, int x, int y) {
6618         return false;
6619     }
6620 
6621     /**
6622      * @deprecated As of JDK version 1.1,
6623      * replaced by processMouseMotionEvent(MouseEvent).
6624      */
6625     @Deprecated
6626     public boolean mouseDrag(Event evt, int x, int y) {
6627         return false;
6628     }
6629 
6630     /**
6631      * @deprecated As of JDK version 1.1,
6632      * replaced by processMouseEvent(MouseEvent).
6633      */
6634     @Deprecated
6635     public boolean mouseUp(Event evt, int x, int y) {
6636         return false;
6637     }
6638 
6639     /**
6640      * @deprecated As of JDK version 1.1,
6641      * replaced by processMouseMotionEvent(MouseEvent).
6642      */
6643     @Deprecated
6644     public boolean mouseMove(Event evt, int x, int y) {
6645         return false;
6646     }
6647 
6648     /**
6649      * @deprecated As of JDK version 1.1,
6650      * replaced by processMouseEvent(MouseEvent).
6651      */
6652     @Deprecated
6653     public boolean mouseEnter(Event evt, int x, int y) {
6654         return false;
6655     }
6656 
6657     /**
6658      * @deprecated As of JDK version 1.1,
6659      * replaced by processMouseEvent(MouseEvent).
6660      */
6661     @Deprecated
6662     public boolean mouseExit(Event evt, int x, int y) {
6663         return false;
6664     }
6665 
6666     /**
6667      * @deprecated As of JDK version 1.1,
6668      * replaced by processKeyEvent(KeyEvent).
6669      */
6670     @Deprecated
6671     public boolean keyDown(Event evt, int key) {
6672         return false;
6673     }
6674 
6675     /**
6676      * @deprecated As of JDK version 1.1,
6677      * replaced by processKeyEvent(KeyEvent).
6678      */
6679     @Deprecated
6680     public boolean keyUp(Event evt, int key) {
6681         return false;
6682     }
6683 
6684     /**
6685      * @deprecated As of JDK version 1.1,
6686      * should register this component as ActionListener on component
6687      * which fires action events.
6688      */
6689     @Deprecated
6690     public boolean action(Event evt, Object what) {
6691         return false;
6692     }
6693 
6694     /**
6695      * Makes this <code>Component</code> displayable by connecting it to a
6696      * native screen resource.
6697      * This method is called internally by the toolkit and should
6698      * not be called directly by programs.
6699      * <p>
6700      * This method changes layout-related information, and therefore,
6701      * invalidates the component hierarchy.
6702      *
6703      * @see       #isDisplayable
6704      * @see       #removeNotify
6705      * @see #invalidate
6706      * @since JDK1.0
6707      */
6708     public void addNotify() {
6709         synchronized (getTreeLock()) {
6710             ComponentPeer peer = this.peer;
6711             if (peer == null || peer instanceof LightweightPeer){
6712                 if (peer == null) {
6713                     // Update both the Component's peer variable and the local
6714                     // variable we use for thread safety.
6715                     this.peer = peer = getToolkit().createComponent(this);
6716                 }
6717 
6718                 // This is a lightweight component which means it won't be
6719                 // able to get window-related events by itself.  If any
6720                 // have been enabled, then the nearest native container must
6721                 // be enabled.
6722                 if (parent != null) {
6723                     long mask = 0;
6724                     if ((mouseListener != null) || ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0)) {
6725                         mask |= AWTEvent.MOUSE_EVENT_MASK;
6726                     }
6727                     if ((mouseMotionListener != null) ||
6728                         ((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0)) {
6729                         mask |= AWTEvent.MOUSE_MOTION_EVENT_MASK;
6730                     }
6731                     if ((mouseWheelListener != null ) ||
6732                         ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0)) {
6733                         mask |= AWTEvent.MOUSE_WHEEL_EVENT_MASK;
6734                     }
6735                     if (focusListener != null || (eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0) {
6736                         mask |= AWTEvent.FOCUS_EVENT_MASK;
6737                     }
6738                     if (keyListener != null || (eventMask & AWTEvent.KEY_EVENT_MASK) != 0) {
6739                         mask |= AWTEvent.KEY_EVENT_MASK;
6740                     }
6741                     if (mask != 0) {
6742                         parent.proxyEnableEvents(mask);
6743                     }
6744                 }
6745             } else {
6746                 // It's native.  If the parent is lightweight it
6747                 // will need some help.
6748                 Container parent = this.parent;
6749                 if (parent != null && parent.peer instanceof LightweightPeer) {
6750                     relocateComponent();
6751                     if (!isRecursivelyVisible()) {
6752                         peer.setVisible(false);
6753                     }
6754                 }
6755             }
6756             invalidate();
6757 
6758             int npopups = (popups != null? popups.size() : 0);
6759             for (int i = 0 ; i < npopups ; i++) {
6760                 PopupMenu popup = (PopupMenu)popups.elementAt(i);
6761                 popup.addNotify();
6762             }
6763 
6764             if (dropTarget != null) dropTarget.addNotify(peer);
6765 
6766             peerFont = getFont();
6767 
6768             if (getContainer() != null && !isAddNotifyComplete) {
6769                 getContainer().increaseComponentCount(this);
6770             }
6771 
6772 
6773             // Update stacking order
6774             updateZOrder();
6775 
6776             if (!isAddNotifyComplete) {
6777                 mixOnShowing();
6778             }
6779 
6780             isAddNotifyComplete = true;
6781 
6782             if (hierarchyListener != null ||
6783                 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
6784                 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) {
6785                 HierarchyEvent e =
6786                     new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED,
6787                                        this, parent,
6788                                        HierarchyEvent.DISPLAYABILITY_CHANGED |
6789                                        ((isRecursivelyVisible())
6790                                         ? HierarchyEvent.SHOWING_CHANGED
6791                                         : 0));
6792                 dispatchEvent(e);
6793             }
6794         }
6795     }
6796 
6797     /**
6798      * Makes this <code>Component</code> undisplayable by destroying it native
6799      * screen resource.
6800      * <p>
6801      * This method is called by the toolkit internally and should
6802      * not be called directly by programs. Code overriding
6803      * this method should call <code>super.removeNotify</code> as
6804      * the first line of the overriding method.
6805      *
6806      * @see       #isDisplayable
6807      * @see       #addNotify
6808      * @since JDK1.0
6809      */
6810     public void removeNotify() {
6811         KeyboardFocusManager.clearMostRecentFocusOwner(this);
6812         if (KeyboardFocusManager.getCurrentKeyboardFocusManager().
6813             getPermanentFocusOwner() == this)
6814         {
6815             KeyboardFocusManager.getCurrentKeyboardFocusManager().
6816                 setGlobalPermanentFocusOwner(null);
6817         }
6818 
6819         synchronized (getTreeLock()) {
6820             if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabledFor(this)) {
6821                 transferFocus(true);
6822             }
6823 
6824             if (getContainer() != null && isAddNotifyComplete) {
6825                 getContainer().decreaseComponentCount(this);
6826             }
6827 
6828             int npopups = (popups != null? popups.size() : 0);
6829             for (int i = 0 ; i < npopups ; i++) {
6830                 PopupMenu popup = (PopupMenu)popups.elementAt(i);
6831                 popup.removeNotify();
6832             }
6833             // If there is any input context for this component, notify
6834             // that this component is being removed. (This has to be done
6835             // before hiding peer.)
6836             if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) {
6837                 InputContext inputContext = getInputContext();
6838                 if (inputContext != null) {
6839                     inputContext.removeNotify(this);
6840                 }
6841             }
6842 
6843             ComponentPeer p = peer;
6844             if (p != null) {
6845                 boolean isLightweight = isLightweight();
6846 
6847                 if (bufferStrategy instanceof FlipBufferStrategy) {
6848                     ((FlipBufferStrategy)bufferStrategy).destroyBuffers();
6849                 }
6850 
6851                 if (dropTarget != null) dropTarget.removeNotify(peer);
6852 
6853                 // Hide peer first to stop system events such as cursor moves.
6854                 if (visible) {
6855                     p.setVisible(false);
6856                 }
6857 
6858                 peer = null; // Stop peer updates.
6859                 peerFont = null;
6860 
6861                 Toolkit.getEventQueue().removeSourceEvents(this, false);
6862                 KeyboardFocusManager.getCurrentKeyboardFocusManager().
6863                     discardKeyEvents(this);
6864 
6865                 p.dispose();
6866 
6867                 mixOnHiding(isLightweight);
6868 
6869                 isAddNotifyComplete = false;
6870                 // Nullifying compoundShape means that the component has normal shape
6871                 // (or has no shape at all).
6872                 this.compoundShape = null;
6873             }
6874 
6875             if (hierarchyListener != null ||
6876                 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
6877                 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) {
6878                 HierarchyEvent e =
6879                     new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED,
6880                                        this, parent,
6881                                        HierarchyEvent.DISPLAYABILITY_CHANGED |
6882                                        ((isRecursivelyVisible())
6883                                         ? HierarchyEvent.SHOWING_CHANGED
6884                                         : 0));
6885                 dispatchEvent(e);
6886             }
6887         }
6888     }
6889 
6890     /**
6891      * @deprecated As of JDK version 1.1,
6892      * replaced by processFocusEvent(FocusEvent).
6893      */
6894     @Deprecated
6895     public boolean gotFocus(Event evt, Object what) {
6896         return false;
6897     }
6898 
6899     /**
6900      * @deprecated As of JDK version 1.1,
6901      * replaced by processFocusEvent(FocusEvent).
6902      */
6903     @Deprecated
6904     public boolean lostFocus(Event evt, Object what) {
6905         return false;
6906     }
6907 
6908     /**
6909      * Returns whether this <code>Component</code> can become the focus
6910      * owner.
6911      *
6912      * @return <code>true</code> if this <code>Component</code> is
6913      * focusable; <code>false</code> otherwise
6914      * @see #setFocusable
6915      * @since JDK1.1
6916      * @deprecated As of 1.4, replaced by <code>isFocusable()</code>.
6917      */
6918     @Deprecated
6919     public boolean isFocusTraversable() {
6920         if (isFocusTraversableOverridden == FOCUS_TRAVERSABLE_UNKNOWN) {
6921             isFocusTraversableOverridden = FOCUS_TRAVERSABLE_DEFAULT;
6922         }
6923         return focusable;
6924     }
6925 
6926     /**
6927      * Returns whether this Component can be focused.
6928      *
6929      * @return <code>true</code> if this Component is focusable;
6930      *         <code>false</code> otherwise.
6931      * @see #setFocusable
6932      * @since 1.4
6933      */
6934     public boolean isFocusable() {
6935         return isFocusTraversable();
6936     }
6937 
6938     /**
6939      * Sets the focusable state of this Component to the specified value. This
6940      * value overrides the Component's default focusability.
6941      *
6942      * @param focusable indicates whether this Component is focusable
6943      * @see #isFocusable
6944      * @since 1.4
6945      * @beaninfo
6946      *       bound: true
6947      */
6948     public void setFocusable(boolean focusable) {
6949         boolean oldFocusable;
6950         synchronized (this) {
6951             oldFocusable = this.focusable;
6952             this.focusable = focusable;
6953         }
6954         isFocusTraversableOverridden = FOCUS_TRAVERSABLE_SET;
6955 
6956         firePropertyChange("focusable", oldFocusable, focusable);
6957         if (oldFocusable && !focusable) {
6958             if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabled()) {
6959                 transferFocus(true);
6960             }
6961             KeyboardFocusManager.clearMostRecentFocusOwner(this);
6962         }
6963     }
6964 
6965     final boolean isFocusTraversableOverridden() {
6966         return (isFocusTraversableOverridden != FOCUS_TRAVERSABLE_DEFAULT);
6967     }
6968 
6969     /**
6970      * Sets the focus traversal keys for a given traversal operation for this
6971      * Component.
6972      * <p>
6973      * The default values for a Component's focus traversal keys are
6974      * implementation-dependent. Sun recommends that all implementations for a
6975      * particular native platform use the same default values. The
6976      * recommendations for Windows and Unix are listed below. These
6977      * recommendations are used in the Sun AWT implementations.
6978      *
6979      * <table border=1 summary="Recommended default values for a Component's focus traversal keys">
6980      * <tr>
6981      *    <th>Identifier</th>
6982      *    <th>Meaning</th>
6983      *    <th>Default</th>
6984      * </tr>
6985      * <tr>
6986      *    <td>KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS</td>
6987      *    <td>Normal forward keyboard traversal</td>
6988      *    <td>TAB on KEY_PRESSED, CTRL-TAB on KEY_PRESSED</td>
6989      * </tr>
6990      * <tr>
6991      *    <td>KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS</td>
6992      *    <td>Normal reverse keyboard traversal</td>
6993      *    <td>SHIFT-TAB on KEY_PRESSED, CTRL-SHIFT-TAB on KEY_PRESSED</td>
6994      * </tr>
6995      * <tr>
6996      *    <td>KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS</td>
6997      *    <td>Go up one focus traversal cycle</td>
6998      *    <td>none</td>
6999      * </tr>
7000      * </table>
7001      *
7002      * To disable a traversal key, use an empty Set; Collections.EMPTY_SET is
7003      * recommended.
7004      * <p>
7005      * Using the AWTKeyStroke API, client code can specify on which of two
7006      * specific KeyEvents, KEY_PRESSED or KEY_RELEASED, the focus traversal
7007      * operation will occur. Regardless of which KeyEvent is specified,
7008      * however, all KeyEvents related to the focus traversal key, including the
7009      * associated KEY_TYPED event, will be consumed, and will not be dispatched
7010      * to any Component. It is a runtime error to specify a KEY_TYPED event as
7011      * mapping to a focus traversal operation, or to map the same event to
7012      * multiple default focus traversal operations.
7013      * <p>
7014      * If a value of null is specified for the Set, this Component inherits the
7015      * Set from its parent. If all ancestors of this Component have null
7016      * specified for the Set, then the current KeyboardFocusManager's default
7017      * Set is used.
7018      *
7019      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7020      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7021      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7022      * @param keystrokes the Set of AWTKeyStroke for the specified operation
7023      * @see #getFocusTraversalKeys
7024      * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
7025      * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
7026      * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
7027      * @throws IllegalArgumentException if id is not one of
7028      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7029      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7030      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or if keystrokes
7031      *         contains null, or if any Object in keystrokes is not an
7032      *         AWTKeyStroke, or if any keystroke represents a KEY_TYPED event,
7033      *         or if any keystroke already maps to another focus traversal
7034      *         operation for this Component
7035      * @since 1.4
7036      * @beaninfo
7037      *       bound: true
7038      */
7039     public void setFocusTraversalKeys(int id,
7040                                       Set<? extends AWTKeyStroke> keystrokes)
7041     {
7042         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {
7043             throw new IllegalArgumentException("invalid focus traversal key identifier");
7044         }
7045 
7046         setFocusTraversalKeys_NoIDCheck(id, keystrokes);
7047     }
7048 
7049     /**
7050      * Returns the Set of focus traversal keys for a given traversal operation
7051      * for this Component. (See
7052      * <code>setFocusTraversalKeys</code> for a full description of each key.)
7053      * <p>
7054      * If a Set of traversal keys has not been explicitly defined for this
7055      * Component, then this Component's parent's Set is returned. If no Set
7056      * has been explicitly defined for any of this Component's ancestors, then
7057      * the current KeyboardFocusManager's default Set is returned.
7058      *
7059      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7060      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7061      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7062      * @return the Set of AWTKeyStrokes for the specified operation. The Set
7063      *         will be unmodifiable, and may be empty. null will never be
7064      *         returned.
7065      * @see #setFocusTraversalKeys
7066      * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
7067      * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
7068      * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
7069      * @throws IllegalArgumentException if id is not one of
7070      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7071      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7072      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7073      * @since 1.4
7074      */
7075     public Set<AWTKeyStroke> getFocusTraversalKeys(int id) {
7076         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {
7077             throw new IllegalArgumentException("invalid focus traversal key identifier");
7078         }
7079 
7080         return getFocusTraversalKeys_NoIDCheck(id);
7081     }
7082 
7083     // We define these methods so that Container does not need to repeat this
7084     // code. Container cannot call super.<method> because Container allows
7085     // DOWN_CYCLE_TRAVERSAL_KEY while Component does not. The Component method
7086     // would erroneously generate an IllegalArgumentException for
7087     // DOWN_CYCLE_TRAVERSAL_KEY.
7088     final void setFocusTraversalKeys_NoIDCheck(int id, Set<? extends AWTKeyStroke> keystrokes) {
7089         Set oldKeys;
7090 
7091         synchronized (this) {
7092             if (focusTraversalKeys == null) {
7093                 initializeFocusTraversalKeys();
7094             }
7095 
7096             if (keystrokes != null) {
7097                 for (Iterator iter = keystrokes.iterator(); iter.hasNext(); ) {
7098                     Object obj = iter.next();
7099 
7100                     if (obj == null) {
7101                         throw new IllegalArgumentException("cannot set null focus traversal key");
7102                     }
7103 
7104                     // Fix for 6195828:
7105                     //According to javadoc this method should throw IAE instead of ClassCastException
7106                     if (!(obj instanceof AWTKeyStroke)) {
7107                         throw new IllegalArgumentException("object is expected to be AWTKeyStroke");
7108                     }
7109                     AWTKeyStroke keystroke = (AWTKeyStroke)obj;
7110 
7111                     if (keystroke.getKeyChar() != KeyEvent.CHAR_UNDEFINED) {
7112                         throw new IllegalArgumentException("focus traversal keys cannot map to KEY_TYPED events");
7113                     }
7114 
7115                     for (int i = 0; i < focusTraversalKeys.length; i++) {
7116                         if (i == id) {
7117                             continue;
7118                         }
7119 
7120                         if (getFocusTraversalKeys_NoIDCheck(i).contains(keystroke))
7121                         {
7122                             throw new IllegalArgumentException("focus traversal keys must be unique for a Component");
7123                         }
7124                     }
7125                 }
7126             }
7127 
7128             oldKeys = focusTraversalKeys[id];
7129             focusTraversalKeys[id] = (keystrokes != null)
7130                 ? Collections.unmodifiableSet(new HashSet(keystrokes))
7131                 : null;
7132         }
7133 
7134         firePropertyChange(focusTraversalKeyPropertyNames[id], oldKeys,
7135                            keystrokes);
7136     }
7137     final Set getFocusTraversalKeys_NoIDCheck(int id) {
7138         // Okay to return Set directly because it is an unmodifiable view
7139         Set keystrokes = (focusTraversalKeys != null)
7140             ? focusTraversalKeys[id]
7141             : null;
7142 
7143         if (keystrokes != null) {
7144             return keystrokes;
7145         } else {
7146             Container parent = this.parent;
7147             if (parent != null) {
7148                 return parent.getFocusTraversalKeys(id);
7149             } else {
7150                 return KeyboardFocusManager.getCurrentKeyboardFocusManager().
7151                     getDefaultFocusTraversalKeys(id);
7152             }
7153         }
7154     }
7155 
7156     /**
7157      * Returns whether the Set of focus traversal keys for the given focus
7158      * traversal operation has been explicitly defined for this Component. If
7159      * this method returns <code>false</code>, this Component is inheriting the
7160      * Set from an ancestor, or from the current KeyboardFocusManager.
7161      *
7162      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7163      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7164      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7165      * @return <code>true</code> if the the Set of focus traversal keys for the
7166      *         given focus traversal operation has been explicitly defined for
7167      *         this Component; <code>false</code> otherwise.
7168      * @throws IllegalArgumentException if id is not one of
7169      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7170      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7171      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7172      * @since 1.4
7173      */
7174     public boolean areFocusTraversalKeysSet(int id) {
7175         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {
7176             throw new IllegalArgumentException("invalid focus traversal key identifier");
7177         }
7178 
7179         return (focusTraversalKeys != null && focusTraversalKeys[id] != null);
7180     }
7181 
7182     /**
7183      * Sets whether focus traversal keys are enabled for this Component.
7184      * Components for which focus traversal keys are disabled receive key
7185      * events for focus traversal keys. Components for which focus traversal
7186      * keys are enabled do not see these events; instead, the events are
7187      * automatically converted to traversal operations.
7188      *
7189      * @param focusTraversalKeysEnabled whether focus traversal keys are
7190      *        enabled for this Component
7191      * @see #getFocusTraversalKeysEnabled
7192      * @see #setFocusTraversalKeys
7193      * @see #getFocusTraversalKeys
7194      * @since 1.4
7195      * @beaninfo
7196      *       bound: true
7197      */
7198     public void setFocusTraversalKeysEnabled(boolean
7199                                              focusTraversalKeysEnabled) {
7200         boolean oldFocusTraversalKeysEnabled;
7201         synchronized (this) {
7202             oldFocusTraversalKeysEnabled = this.focusTraversalKeysEnabled;
7203             this.focusTraversalKeysEnabled = focusTraversalKeysEnabled;
7204         }
7205         firePropertyChange("focusTraversalKeysEnabled",
7206                            oldFocusTraversalKeysEnabled,
7207                            focusTraversalKeysEnabled);
7208     }
7209 
7210     /**
7211      * Returns whether focus traversal keys are enabled for this Component.
7212      * Components for which focus traversal keys are disabled receive key
7213      * events for focus traversal keys. Components for which focus traversal
7214      * keys are enabled do not see these events; instead, the events are
7215      * automatically converted to traversal operations.
7216      *
7217      * @return whether focus traversal keys are enabled for this Component
7218      * @see #setFocusTraversalKeysEnabled
7219      * @see #setFocusTraversalKeys
7220      * @see #getFocusTraversalKeys
7221      * @since 1.4
7222      */
7223     public boolean getFocusTraversalKeysEnabled() {
7224         return focusTraversalKeysEnabled;
7225     }
7226 
7227     /**
7228      * Requests that this Component get the input focus, and that this
7229      * Component's top-level ancestor become the focused Window. This
7230      * component must be displayable, focusable, visible and all of
7231      * its ancestors (with the exception of the top-level Window) must
7232      * be visible for the request to be granted. Every effort will be
7233      * made to honor the request; however, in some cases it may be
7234      * impossible to do so. Developers must never assume that this
7235      * Component is the focus owner until this Component receives a
7236      * FOCUS_GAINED event. If this request is denied because this
7237      * Component's top-level Window cannot become the focused Window,
7238      * the request will be remembered and will be granted when the
7239      * Window is later focused by the user.
7240      * <p>
7241      * This method cannot be used to set the focus owner to no Component at
7242      * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code>
7243      * instead.
7244      * <p>
7245      * Because the focus behavior of this method is platform-dependent,
7246      * developers are strongly encouraged to use
7247      * <code>requestFocusInWindow</code> when possible.
7248      *
7249      * <p>Note: Not all focus transfers result from invoking this method. As
7250      * such, a component may receive focus without this or any of the other
7251      * {@code requestFocus} methods of {@code Component} being invoked.
7252      *
7253      * @see #requestFocusInWindow
7254      * @see java.awt.event.FocusEvent
7255      * @see #addFocusListener
7256      * @see #isFocusable
7257      * @see #isDisplayable
7258      * @see KeyboardFocusManager#clearGlobalFocusOwner
7259      * @since JDK1.0
7260      */
7261     public void requestFocus() {
7262         requestFocusHelper(false, true);
7263     }
7264 
7265     boolean requestFocus(CausedFocusEvent.Cause cause) {
7266         return requestFocusHelper(false, true, cause);
7267     }
7268 
7269     /**
7270      * Requests that this <code>Component</code> get the input focus,
7271      * and that this <code>Component</code>'s top-level ancestor
7272      * become the focused <code>Window</code>. This component must be
7273      * displayable, focusable, visible and all of its ancestors (with
7274      * the exception of the top-level Window) must be visible for the
7275      * request to be granted. Every effort will be made to honor the
7276      * request; however, in some cases it may be impossible to do
7277      * so. Developers must never assume that this component is the
7278      * focus owner until this component receives a FOCUS_GAINED
7279      * event. If this request is denied because this component's
7280      * top-level window cannot become the focused window, the request
7281      * will be remembered and will be granted when the window is later
7282      * focused by the user.
7283      * <p>
7284      * This method returns a boolean value. If <code>false</code> is returned,
7285      * the request is <b>guaranteed to fail</b>. If <code>true</code> is
7286      * returned, the request will succeed <b>unless</b> it is vetoed, or an
7287      * extraordinary event, such as disposal of the component's peer, occurs
7288      * before the request can be granted by the native windowing system. Again,
7289      * while a return value of <code>true</code> indicates that the request is
7290      * likely to succeed, developers must never assume that this component is
7291      * the focus owner until this component receives a FOCUS_GAINED event.
7292      * <p>
7293      * This method cannot be used to set the focus owner to no component at
7294      * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner</code>
7295      * instead.
7296      * <p>
7297      * Because the focus behavior of this method is platform-dependent,
7298      * developers are strongly encouraged to use
7299      * <code>requestFocusInWindow</code> when possible.
7300      * <p>
7301      * Every effort will be made to ensure that <code>FocusEvent</code>s
7302      * generated as a
7303      * result of this request will have the specified temporary value. However,
7304      * because specifying an arbitrary temporary state may not be implementable
7305      * on all native windowing systems, correct behavior for this method can be
7306      * guaranteed only for lightweight <code>Component</code>s.
7307      * This method is not intended
7308      * for general use, but exists instead as a hook for lightweight component
7309      * libraries, such as Swing.
7310      *
7311      * <p>Note: Not all focus transfers result from invoking this method. As
7312      * such, a component may receive focus without this or any of the other
7313      * {@code requestFocus} methods of {@code Component} being invoked.
7314      *
7315      * @param temporary true if the focus change is temporary,
7316      *        such as when the window loses the focus; for
7317      *        more information on temporary focus changes see the
7318      *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
7319      * @return <code>false</code> if the focus change request is guaranteed to
7320      *         fail; <code>true</code> if it is likely to succeed
7321      * @see java.awt.event.FocusEvent
7322      * @see #addFocusListener
7323      * @see #isFocusable
7324      * @see #isDisplayable
7325      * @see KeyboardFocusManager#clearGlobalFocusOwner
7326      * @since 1.4
7327      */
7328     protected boolean requestFocus(boolean temporary) {
7329         return requestFocusHelper(temporary, true);
7330     }
7331 
7332     boolean requestFocus(boolean temporary, CausedFocusEvent.Cause cause) {
7333         return requestFocusHelper(temporary, true, cause);
7334     }
7335     /**
7336      * Requests that this Component get the input focus, if this
7337      * Component's top-level ancestor is already the focused
7338      * Window. This component must be displayable, focusable, visible
7339      * and all of its ancestors (with the exception of the top-level
7340      * Window) must be visible for the request to be granted. Every
7341      * effort will be made to honor the request; however, in some
7342      * cases it may be impossible to do so. Developers must never
7343      * assume that this Component is the focus owner until this
7344      * Component receives a FOCUS_GAINED event.
7345      * <p>
7346      * This method returns a boolean value. If <code>false</code> is returned,
7347      * the request is <b>guaranteed to fail</b>. If <code>true</code> is
7348      * returned, the request will succeed <b>unless</b> it is vetoed, or an
7349      * extraordinary event, such as disposal of the Component's peer, occurs
7350      * before the request can be granted by the native windowing system. Again,
7351      * while a return value of <code>true</code> indicates that the request is
7352      * likely to succeed, developers must never assume that this Component is
7353      * the focus owner until this Component receives a FOCUS_GAINED event.
7354      * <p>
7355      * This method cannot be used to set the focus owner to no Component at
7356      * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code>
7357      * instead.
7358      * <p>
7359      * The focus behavior of this method can be implemented uniformly across
7360      * platforms, and thus developers are strongly encouraged to use this
7361      * method over <code>requestFocus</code> when possible. Code which relies
7362      * on <code>requestFocus</code> may exhibit different focus behavior on
7363      * different platforms.
7364      *
7365      * <p>Note: Not all focus transfers result from invoking this method. As
7366      * such, a component may receive focus without this or any of the other
7367      * {@code requestFocus} methods of {@code Component} being invoked.
7368      *
7369      * @return <code>false</code> if the focus change request is guaranteed to
7370      *         fail; <code>true</code> if it is likely to succeed
7371      * @see #requestFocus
7372      * @see java.awt.event.FocusEvent
7373      * @see #addFocusListener
7374      * @see #isFocusable
7375      * @see #isDisplayable
7376      * @see KeyboardFocusManager#clearGlobalFocusOwner
7377      * @since 1.4
7378      */
7379     public boolean requestFocusInWindow() {
7380         return requestFocusHelper(false, false);
7381     }
7382 
7383     boolean requestFocusInWindow(CausedFocusEvent.Cause cause) {
7384         return requestFocusHelper(false, false, cause);
7385     }
7386 
7387     /**
7388      * Requests that this <code>Component</code> get the input focus,
7389      * if this <code>Component</code>'s top-level ancestor is already
7390      * the focused <code>Window</code>.  This component must be
7391      * displayable, focusable, visible and all of its ancestors (with
7392      * the exception of the top-level Window) must be visible for the
7393      * request to be granted. Every effort will be made to honor the
7394      * request; however, in some cases it may be impossible to do
7395      * so. Developers must never assume that this component is the
7396      * focus owner until this component receives a FOCUS_GAINED event.
7397      * <p>
7398      * This method returns a boolean value. If <code>false</code> is returned,
7399      * the request is <b>guaranteed to fail</b>. If <code>true</code> is
7400      * returned, the request will succeed <b>unless</b> it is vetoed, or an
7401      * extraordinary event, such as disposal of the component's peer, occurs
7402      * before the request can be granted by the native windowing system. Again,
7403      * while a return value of <code>true</code> indicates that the request is
7404      * likely to succeed, developers must never assume that this component is
7405      * the focus owner until this component receives a FOCUS_GAINED event.
7406      * <p>
7407      * This method cannot be used to set the focus owner to no component at
7408      * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner</code>
7409      * instead.
7410      * <p>
7411      * The focus behavior of this method can be implemented uniformly across
7412      * platforms, and thus developers are strongly encouraged to use this
7413      * method over <code>requestFocus</code> when possible. Code which relies
7414      * on <code>requestFocus</code> may exhibit different focus behavior on
7415      * different platforms.
7416      * <p>
7417      * Every effort will be made to ensure that <code>FocusEvent</code>s
7418      * generated as a
7419      * result of this request will have the specified temporary value. However,
7420      * because specifying an arbitrary temporary state may not be implementable
7421      * on all native windowing systems, correct behavior for this method can be
7422      * guaranteed only for lightweight components. This method is not intended
7423      * for general use, but exists instead as a hook for lightweight component
7424      * libraries, such as Swing.
7425      *
7426      * <p>Note: Not all focus transfers result from invoking this method. As
7427      * such, a component may receive focus without this or any of the other
7428      * {@code requestFocus} methods of {@code Component} being invoked.
7429      *
7430      * @param temporary true if the focus change is temporary,
7431      *        such as when the window loses the focus; for
7432      *        more information on temporary focus changes see the
7433      *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
7434      * @return <code>false</code> if the focus change request is guaranteed to
7435      *         fail; <code>true</code> if it is likely to succeed
7436      * @see #requestFocus
7437      * @see java.awt.event.FocusEvent
7438      * @see #addFocusListener
7439      * @see #isFocusable
7440      * @see #isDisplayable
7441      * @see KeyboardFocusManager#clearGlobalFocusOwner
7442      * @since 1.4
7443      */
7444     protected boolean requestFocusInWindow(boolean temporary) {
7445         return requestFocusHelper(temporary, false);
7446     }
7447 
7448     boolean requestFocusInWindow(boolean temporary, CausedFocusEvent.Cause cause) {
7449         return requestFocusHelper(temporary, false, cause);
7450     }
7451 
7452     final boolean requestFocusHelper(boolean temporary,
7453                                      boolean focusedWindowChangeAllowed) {
7454         return requestFocusHelper(temporary, focusedWindowChangeAllowed, CausedFocusEvent.Cause.UNKNOWN);
7455     }
7456 
7457     final boolean requestFocusHelper(boolean temporary,
7458                                      boolean focusedWindowChangeAllowed,
7459                                      CausedFocusEvent.Cause cause)
7460     {
7461         if (!isRequestFocusAccepted(temporary, focusedWindowChangeAllowed, cause)) {
7462             if (focusLog.isLoggable(Level.FINEST)) {
7463                 focusLog.log(Level.FINEST, "requestFocus is not accepted");
7464             }
7465             return false;
7466         }
7467 
7468         // Update most-recent map
7469         KeyboardFocusManager.setMostRecentFocusOwner(this);
7470 
7471         Component window = this;
7472         while ( (window != null) && !(window instanceof Window)) {
7473             if (!window.isVisible()) {
7474                 if (focusLog.isLoggable(Level.FINEST)) {
7475                     focusLog.log(Level.FINEST, "component is recurively invisible");
7476                 }
7477                 return false;
7478             }
7479             window = window.parent;
7480         }
7481 
7482         ComponentPeer peer = this.peer;
7483         Component heavyweight = (peer instanceof LightweightPeer)
7484             ? getNativeContainer() : this;
7485         if (heavyweight == null || !heavyweight.isVisible()) {
7486             if (focusLog.isLoggable(Level.FINEST)) {
7487                 focusLog.log(Level.FINEST, "Component is not a part of visible hierarchy");
7488             }
7489             return false;
7490         }
7491         peer = heavyweight.peer;
7492         if (peer == null) {
7493             if (focusLog.isLoggable(Level.FINEST)) {
7494                 focusLog.log(Level.FINEST, "Peer is null");
7495             }
7496             return false;
7497         }
7498 
7499         // Focus this Component
7500         long time = EventQueue.getMostRecentEventTime();
7501         boolean success = peer.requestFocus
7502             (this, temporary, focusedWindowChangeAllowed, time, cause);
7503         if (!success) {
7504             KeyboardFocusManager.getCurrentKeyboardFocusManager
7505                 (appContext).dequeueKeyEvents(time, this);
7506             if (focusLog.isLoggable(Level.FINEST)) {
7507                 focusLog.log(Level.FINEST, "Peer request failed");
7508             }
7509         } else {
7510             if (focusLog.isLoggable(Level.FINEST)) {
7511                 focusLog.log(Level.FINEST, "Pass for " + this);
7512             }
7513         }
7514         return success;
7515     }
7516 
7517     private boolean isRequestFocusAccepted(boolean temporary,
7518                                            boolean focusedWindowChangeAllowed,
7519                                            CausedFocusEvent.Cause cause)
7520     {
7521         if (!isFocusable() || !isVisible()) {
7522             if (focusLog.isLoggable(Level.FINEST)) {
7523                 focusLog.log(Level.FINEST, "Not focusable or not visible");
7524             }
7525             return false;
7526         }
7527 
7528         ComponentPeer peer = this.peer;
7529         if (peer == null) {
7530             if (focusLog.isLoggable(Level.FINEST)) {
7531                 focusLog.log(Level.FINEST, "peer is null");
7532             }
7533             return false;
7534         }
7535 
7536         Window window = getContainingWindow();
7537         if (window == null || !((Window)window).isFocusableWindow()) {
7538             if (focusLog.isLoggable(Level.FINEST)) {
7539                 focusLog.log(Level.FINEST, "Component doesn't have toplevel");
7540             }
7541             return false;
7542         }
7543 
7544         // We have passed all regular checks for focus request,
7545         // now let's call RequestFocusController and see what it says.
7546         Component focusOwner = KeyboardFocusManager.getMostRecentFocusOwner(window);
7547         if (focusOwner == null) {
7548             // sometimes most recent focus owner may be null, but focus owner is not
7549             // e.g. we reset most recent focus owner if user removes focus owner
7550             focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
7551             if (focusOwner != null && focusOwner.getContainingWindow() != window) {
7552                 focusOwner = null;
7553             }
7554         }
7555 
7556         if (focusOwner == this || focusOwner == null) {
7557             // Controller is supposed to verify focus transfers and for this it
7558             // should know both from and to components.  And it shouldn't verify
7559             // transfers from when these components are equal.
7560             if (focusLog.isLoggable(Level.FINEST)) {
7561                 focusLog.log(Level.FINEST, "focus owner is null or this");
7562             }
7563             return true;
7564         }
7565 
7566         if (CausedFocusEvent.Cause.ACTIVATION == cause) {
7567             // we shouldn't call RequestFocusController in case we are
7568             // in activation.  We do request focus on component which
7569             // has got temporary focus lost and then on component which is
7570             // most recent focus owner.  But most recent focus owner can be
7571             // changed by requestFocsuXXX() call only, so this transfer has
7572             // been already approved.
7573             if (focusLog.isLoggable(Level.FINEST)) {
7574                 focusLog.log(Level.FINEST, "cause is activation");
7575             }
7576             return true;
7577         }
7578 
7579         boolean ret = Component.requestFocusController.acceptRequestFocus(focusOwner,
7580                                                                           this,
7581                                                                           temporary,
7582                                                                           focusedWindowChangeAllowed,
7583                                                                           cause);
7584         if (focusLog.isLoggable(Level.FINEST)) {
7585             focusLog.log(Level.FINEST, "RequestFocusController returns {0}", ret);
7586         }
7587 
7588         return ret;
7589     }
7590 
7591     private static RequestFocusController requestFocusController = new DummyRequestFocusController();
7592 
7593     // Swing access this method through reflection to implement InputVerifier's functionality.
7594     // Perhaps, we should make this method public (later ;)
7595     private static class DummyRequestFocusController implements RequestFocusController {
7596         public boolean acceptRequestFocus(Component from, Component to,
7597                                           boolean temporary, boolean focusedWindowChangeAllowed,
7598                                           CausedFocusEvent.Cause cause)
7599         {
7600             return true;
7601         }
7602     };
7603 
7604     synchronized static void setRequestFocusController(RequestFocusController requestController)
7605     {
7606         if (requestController == null) {
7607             requestFocusController = new DummyRequestFocusController();
7608         } else {
7609             requestFocusController = requestController;
7610         }
7611     }
7612 
7613     /**
7614      * Returns the Container which is the focus cycle root of this Component's
7615      * focus traversal cycle. Each focus traversal cycle has only a single
7616      * focus cycle root and each Component which is not a Container belongs to
7617      * only a single focus traversal cycle. Containers which are focus cycle
7618      * roots belong to two cycles: one rooted at the Container itself, and one
7619      * rooted at the Container's nearest focus-cycle-root ancestor. For such
7620      * Containers, this method will return the Container's nearest focus-cycle-
7621      * root ancestor.
7622      *
7623      * @return this Component's nearest focus-cycle-root ancestor
7624      * @see Container#isFocusCycleRoot()
7625      * @since 1.4
7626      */
7627     public Container getFocusCycleRootAncestor() {
7628         Container rootAncestor = this.parent;
7629         while (rootAncestor != null && !rootAncestor.isFocusCycleRoot()) {
7630             rootAncestor = rootAncestor.parent;
7631         }
7632         return rootAncestor;
7633     }
7634 
7635     /**
7636      * Returns whether the specified Container is the focus cycle root of this
7637      * Component's focus traversal cycle. Each focus traversal cycle has only
7638      * a single focus cycle root and each Component which is not a Container
7639      * belongs to only a single focus traversal cycle.
7640      *
7641      * @param container the Container to be tested
7642      * @return <code>true</code> if the specified Container is a focus-cycle-
7643      *         root of this Component; <code>false</code> otherwise
7644      * @see Container#isFocusCycleRoot()
7645      * @since 1.4
7646      */
7647     public boolean isFocusCycleRoot(Container container) {
7648         Container rootAncestor = getFocusCycleRootAncestor();
7649         return (rootAncestor == container);
7650     }
7651 
7652     Container getTraversalRoot() {
7653         return getFocusCycleRootAncestor();
7654     }
7655 
7656     /**
7657      * Transfers the focus to the next component, as though this Component were
7658      * the focus owner.
7659      * @see       #requestFocus()
7660      * @since     JDK1.1
7661      */
7662     public void transferFocus() {
7663         nextFocus();
7664     }
7665 
7666     /**
7667      * @deprecated As of JDK version 1.1,
7668      * replaced by transferFocus().
7669      */
7670     @Deprecated
7671     public void nextFocus() {
7672         transferFocus(false);
7673     }
7674 
7675     boolean transferFocus(boolean clearOnFailure) {
7676         if (focusLog.isLoggable(Level.FINER)) {
7677             focusLog.finer("clearOnFailure = " + clearOnFailure);
7678         }
7679         Component toFocus = getNextFocusCandidate();
7680         boolean res = false;
7681         if (toFocus != null && !toFocus.isFocusOwner() && toFocus != this) {
7682             res = toFocus.requestFocusInWindow(CausedFocusEvent.Cause.TRAVERSAL_FORWARD);
7683         }
7684         if (clearOnFailure && !res) {
7685             if (focusLog.isLoggable(Level.FINER)) {
7686                 focusLog.finer("clear global focus owner");
7687             }
7688             KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
7689         }
7690         if (focusLog.isLoggable(Level.FINER)) {
7691             focusLog.finer("returning result: " + res);
7692         }
7693         return res;
7694     }
7695 
7696     final Component getNextFocusCandidate() {
7697         Container rootAncestor = getTraversalRoot();
7698         Component comp = this;
7699         while (rootAncestor != null &&
7700                !(rootAncestor.isShowing() && rootAncestor.canBeFocusOwner()))
7701         {
7702             comp = rootAncestor;
7703             rootAncestor = comp.getFocusCycleRootAncestor();
7704         }
7705         if (focusLog.isLoggable(Level.FINER)) {
7706             focusLog.finer("comp = " + comp + ", root = " + rootAncestor);
7707         }
7708         Component candidate = null;
7709         if (rootAncestor != null) {
7710             FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy();
7711             Component toFocus = policy.getComponentAfter(rootAncestor, comp);
7712             if (focusLog.isLoggable(Level.FINER)) {
7713                 focusLog.finer("component after is " + toFocus);
7714             }
7715             if (toFocus == null) {
7716                 toFocus = policy.getDefaultComponent(rootAncestor);
7717                 if (focusLog.isLoggable(Level.FINER)) {
7718                     focusLog.finer("default component is " + toFocus);
7719                 }
7720             }
7721             if (toFocus == null) {
7722                 Applet applet = EmbeddedFrame.getAppletIfAncestorOf(this);
7723                 if (applet != null) {
7724                     toFocus = applet;
7725                 }
7726             }
7727             candidate = toFocus;
7728         }
7729         if (focusLog.isLoggable(Level.FINER)) {
7730             focusLog.finer("Focus transfer candidate: " + candidate);
7731         }
7732         return candidate;
7733     }
7734 
7735     /**
7736      * Transfers the focus to the previous component, as though this Component
7737      * were the focus owner.
7738      * @see       #requestFocus()
7739      * @since     1.4
7740      */
7741     public void transferFocusBackward() {
7742         transferFocusBackward(false);
7743     }
7744 
7745     boolean transferFocusBackward(boolean clearOnFailure) {
7746         Container rootAncestor = getTraversalRoot();
7747         Component comp = this;
7748         while (rootAncestor != null &&
7749                !(rootAncestor.isShowing() && rootAncestor.canBeFocusOwner()))
7750         {
7751             comp = rootAncestor;
7752             rootAncestor = comp.getFocusCycleRootAncestor();
7753         }
7754         boolean res = false;
7755         if (rootAncestor != null) {
7756             FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy();
7757             Component toFocus = policy.getComponentBefore(rootAncestor, comp);
7758             if (toFocus == null) {
7759                 toFocus = policy.getDefaultComponent(rootAncestor);
7760             }
7761             if (toFocus != null) {
7762                 res = toFocus.requestFocusInWindow(CausedFocusEvent.Cause.TRAVERSAL_BACKWARD);
7763             }
7764         }
7765         if (!res) {
7766             if (focusLog.isLoggable(Level.FINER)) {
7767                 focusLog.finer("clear global focus owner");
7768             }
7769             KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
7770         }
7771         if (focusLog.isLoggable(Level.FINER)) {
7772             focusLog.finer("returning result: " + res);
7773         }
7774         return res;
7775     }
7776 
7777     /**
7778      * Transfers the focus up one focus traversal cycle. Typically, the focus
7779      * owner is set to this Component's focus cycle root, and the current focus
7780      * cycle root is set to the new focus owner's focus cycle root. If,
7781      * however, this Component's focus cycle root is a Window, then the focus
7782      * owner is set to the focus cycle root's default Component to focus, and
7783      * the current focus cycle root is unchanged.
7784      *
7785      * @see       #requestFocus()
7786      * @see       Container#isFocusCycleRoot()
7787      * @see       Container#setFocusCycleRoot(boolean)
7788      * @since     1.4
7789      */
7790     public void transferFocusUpCycle() {
7791         Container rootAncestor;
7792         for (rootAncestor = getFocusCycleRootAncestor();
7793              rootAncestor != null && !(rootAncestor.isShowing() &&
7794                                        rootAncestor.isFocusable() &&
7795                                        rootAncestor.isEnabled());
7796              rootAncestor = rootAncestor.getFocusCycleRootAncestor()) {
7797         }
7798 
7799         if (rootAncestor != null) {
7800             Container rootAncestorRootAncestor =
7801                 rootAncestor.getFocusCycleRootAncestor();
7802             KeyboardFocusManager.getCurrentKeyboardFocusManager().
7803                 setGlobalCurrentFocusCycleRoot(
7804                                                (rootAncestorRootAncestor != null)
7805                                                ? rootAncestorRootAncestor
7806                                                : rootAncestor);
7807             rootAncestor.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_UP);
7808         } else {
7809             Window window = getContainingWindow();
7810 
7811             if (window != null) {
7812                 Component toFocus = window.getFocusTraversalPolicy().
7813                     getDefaultComponent(window);
7814                 if (toFocus != null) {
7815                     KeyboardFocusManager.getCurrentKeyboardFocusManager().
7816                         setGlobalCurrentFocusCycleRoot(window);
7817                     toFocus.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_UP);
7818                 }
7819             }
7820         }
7821     }
7822 
7823     /**
7824      * Returns <code>true</code> if this <code>Component</code> is the
7825      * focus owner.  This method is obsolete, and has been replaced by
7826      * <code>isFocusOwner()</code>.
7827      *
7828      * @return <code>true</code> if this <code>Component</code> is the
7829      *         focus owner; <code>false</code> otherwise
7830      * @since 1.2
7831      */
7832     public boolean hasFocus() {
7833         return (KeyboardFocusManager.getCurrentKeyboardFocusManager().
7834                 getFocusOwner() == this);
7835     }
7836 
7837     /**
7838      * Returns <code>true</code> if this <code>Component</code> is the
7839      *    focus owner.
7840      *
7841      * @return <code>true</code> if this <code>Component</code> is the
7842      *     focus owner; <code>false</code> otherwise
7843      * @since 1.4
7844      */
7845     public boolean isFocusOwner() {
7846         return hasFocus();
7847     }
7848 
7849     /*
7850      * Used to disallow auto-focus-transfer on disposal of the focus owner
7851      * in the process of disposing its parent container.
7852      */
7853     private boolean autoFocusTransferOnDisposal = true;
7854 
7855     void setAutoFocusTransferOnDisposal(boolean value) {
7856         autoFocusTransferOnDisposal = value;
7857     }
7858 
7859     boolean isAutoFocusTransferOnDisposal() {
7860         return autoFocusTransferOnDisposal;
7861     }
7862 
7863     /**
7864      * Adds the specified popup menu to the component.
7865      * @param     popup the popup menu to be added to the component.
7866      * @see       #remove(MenuComponent)
7867      * @exception NullPointerException if {@code popup} is {@code null}
7868      * @since     JDK1.1
7869      */
7870     public void add(PopupMenu popup) {
7871         synchronized (getTreeLock()) {
7872             if (popup.parent != null) {
7873                 popup.parent.remove(popup);
7874             }
7875             if (popups == null) {
7876                 popups = new Vector();
7877             }
7878             popups.addElement(popup);
7879             popup.parent = this;
7880 
7881             if (peer != null) {
7882                 if (popup.peer == null) {
7883                     popup.addNotify();
7884                 }
7885             }
7886         }
7887     }
7888 
7889     /**
7890      * Removes the specified popup menu from the component.
7891      * @param     popup the popup menu to be removed
7892      * @see       #add(PopupMenu)
7893      * @since     JDK1.1
7894      */
7895     public void remove(MenuComponent popup) {
7896         synchronized (getTreeLock()) {
7897             if (popups == null) {
7898                 return;
7899             }
7900             int index = popups.indexOf(popup);
7901             if (index >= 0) {
7902                 PopupMenu pmenu = (PopupMenu)popup;
7903                 if (pmenu.peer != null) {
7904                     pmenu.removeNotify();
7905                 }
7906                 pmenu.parent = null;
7907                 popups.removeElementAt(index);
7908                 if (popups.size() == 0) {
7909                     popups = null;
7910                 }
7911             }
7912         }
7913     }
7914 
7915     /**
7916      * Returns a string representing the state of this component. This
7917      * method is intended to be used only for debugging purposes, and the
7918      * content and format of the returned string may vary between
7919      * implementations. The returned string may be empty but may not be
7920      * <code>null</code>.
7921      *
7922      * @return  a string representation of this component's state
7923      * @since     JDK1.0
7924      */
7925     protected String paramString() {
7926         String thisName = getName();
7927         String str = (thisName != null? thisName : "") + "," + x + "," + y + "," + width + "x" + height;
7928         if (!isValid()) {
7929             str += ",invalid";
7930         }
7931         if (!visible) {
7932             str += ",hidden";
7933         }
7934         if (!enabled) {
7935             str += ",disabled";
7936         }
7937         return str;
7938     }
7939 
7940     /**
7941      * Returns a string representation of this component and its values.
7942      * @return    a string representation of this component
7943      * @since     JDK1.0
7944      */
7945     public String toString() {
7946         return getClass().getName() + "[" + paramString() + "]";
7947     }
7948 
7949     /**
7950      * Prints a listing of this component to the standard system output
7951      * stream <code>System.out</code>.
7952      * @see       java.lang.System#out
7953      * @since     JDK1.0
7954      */
7955     public void list() {
7956         list(System.out, 0);
7957     }
7958 
7959     /**
7960      * Prints a listing of this component to the specified output
7961      * stream.
7962      * @param    out   a print stream
7963      * @since    JDK1.0
7964      */
7965     public void list(PrintStream out) {
7966         list(out, 0);
7967     }
7968 
7969     /**
7970      * Prints out a list, starting at the specified indentation, to the
7971      * specified print stream.
7972      * @param     out      a print stream
7973      * @param     indent   number of spaces to indent
7974      * @see       java.io.PrintStream#println(java.lang.Object)
7975      * @since     JDK1.0
7976      */
7977     public void list(PrintStream out, int indent) {
7978         for (int i = 0 ; i < indent ; i++) {
7979             out.print(" ");
7980         }
7981         out.println(this);
7982     }
7983 
7984     /**
7985      * Prints a listing to the specified print writer.
7986      * @param  out  the print writer to print to
7987      * @since JDK1.1
7988      */
7989     public void list(PrintWriter out) {
7990         list(out, 0);
7991     }
7992 
7993     /**
7994      * Prints out a list, starting at the specified indentation, to
7995      * the specified print writer.
7996      * @param out the print writer to print to
7997      * @param indent the number of spaces to indent
7998      * @see       java.io.PrintStream#println(java.lang.Object)
7999      * @since JDK1.1
8000      */
8001     public void list(PrintWriter out, int indent) {
8002         for (int i = 0 ; i < indent ; i++) {
8003             out.print(" ");
8004         }
8005         out.println(this);
8006     }
8007 
8008     /*
8009      * Fetches the native container somewhere higher up in the component
8010      * tree that contains this component.
8011      */
8012     Container getNativeContainer() {
8013         Container p = parent;
8014         while (p != null && p.peer instanceof LightweightPeer) {
8015             p = p.getParent();
8016         }
8017         return p;
8018     }
8019 
8020     /**
8021      * Adds a PropertyChangeListener to the listener list. The listener is
8022      * registered for all bound properties of this class, including the
8023      * following:
8024      * <ul>
8025      *    <li>this Component's font ("font")</li>
8026      *    <li>this Component's background color ("background")</li>
8027      *    <li>this Component's foreground color ("foreground")</li>
8028      *    <li>this Component's focusability ("focusable")</li>
8029      *    <li>this Component's focus traversal keys enabled state
8030      *        ("focusTraversalKeysEnabled")</li>
8031      *    <li>this Component's Set of FORWARD_TRAVERSAL_KEYS
8032      *        ("forwardFocusTraversalKeys")</li>
8033      *    <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS
8034      *        ("backwardFocusTraversalKeys")</li>
8035      *    <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS
8036      *        ("upCycleFocusTraversalKeys")</li>
8037      *    <li>this Component's preferred size ("preferredSize")</li>
8038      *    <li>this Component's minimum size ("minimumSize")</li>
8039      *    <li>this Component's maximum size ("maximumSize")</li>
8040      *    <li>this Component's name ("name")</li>
8041      * </ul>
8042      * Note that if this <code>Component</code> is inheriting a bound property, then no
8043      * event will be fired in response to a change in the inherited property.
8044      * <p>
8045      * If <code>listener</code> is <code>null</code>,
8046      * no exception is thrown and no action is performed.
8047      *
8048      * @param    listener  the property change listener to be added
8049      *
8050      * @see #removePropertyChangeListener
8051      * @see #getPropertyChangeListeners
8052      * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8053      */
8054     public void addPropertyChangeListener(
8055                                                        PropertyChangeListener listener) {
8056         synchronized (getObjectLock()) {
8057             if (listener == null) {
8058                 return;
8059             }
8060             if (changeSupport == null) {
8061                 changeSupport = new PropertyChangeSupport(this);
8062             }
8063             changeSupport.addPropertyChangeListener(listener);
8064         }
8065     }
8066 
8067     /**
8068      * Removes a PropertyChangeListener from the listener list. This method
8069      * should be used to remove PropertyChangeListeners that were registered
8070      * for all bound properties of this class.
8071      * <p>
8072      * If listener is null, no exception is thrown and no action is performed.
8073      *
8074      * @param listener the PropertyChangeListener to be removed
8075      *
8076      * @see #addPropertyChangeListener
8077      * @see #getPropertyChangeListeners
8078      * @see #removePropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener)
8079      */
8080     public void removePropertyChangeListener(
8081                                                           PropertyChangeListener listener) {
8082         synchronized (getObjectLock()) {
8083             if (listener == null || changeSupport == null) {
8084                 return;
8085             }
8086             changeSupport.removePropertyChangeListener(listener);
8087         }
8088     }
8089 
8090     /**
8091      * Returns an array of all the property change listeners
8092      * registered on this component.
8093      *
8094      * @return all of this component's <code>PropertyChangeListener</code>s
8095      *         or an empty array if no property change
8096      *         listeners are currently registered
8097      *
8098      * @see      #addPropertyChangeListener
8099      * @see      #removePropertyChangeListener
8100      * @see      #getPropertyChangeListeners(java.lang.String)
8101      * @see      java.beans.PropertyChangeSupport#getPropertyChangeListeners
8102      * @since    1.4
8103      */
8104     public PropertyChangeListener[] getPropertyChangeListeners() {
8105         synchronized (getObjectLock()) {
8106             if (changeSupport == null) {
8107                 return new PropertyChangeListener[0];
8108             }
8109             return changeSupport.getPropertyChangeListeners();
8110         }
8111     }
8112 
8113     /**
8114      * Adds a PropertyChangeListener to the listener list for a specific
8115      * property. The specified property may be user-defined, or one of the
8116      * following:
8117      * <ul>
8118      *    <li>this Component's font ("font")</li>
8119      *    <li>this Component's background color ("background")</li>
8120      *    <li>this Component's foreground color ("foreground")</li>
8121      *    <li>this Component's focusability ("focusable")</li>
8122      *    <li>this Component's focus traversal keys enabled state
8123      *        ("focusTraversalKeysEnabled")</li>
8124      *    <li>this Component's Set of FORWARD_TRAVERSAL_KEYS
8125      *        ("forwardFocusTraversalKeys")</li>
8126      *    <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS
8127      *        ("backwardFocusTraversalKeys")</li>
8128      *    <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS
8129      *        ("upCycleFocusTraversalKeys")</li>
8130      * </ul>
8131      * Note that if this <code>Component</code> is inheriting a bound property, then no
8132      * event will be fired in response to a change in the inherited property.
8133      * <p>
8134      * If <code>propertyName</code> or <code>listener</code> is <code>null</code>,
8135      * no exception is thrown and no action is taken.
8136      *
8137      * @param propertyName one of the property names listed above
8138      * @param listener the property change listener to be added
8139      *
8140      * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8141      * @see #getPropertyChangeListeners(java.lang.String)
8142      * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8143      */
8144     public void addPropertyChangeListener(
8145                                                        String propertyName,
8146                                                        PropertyChangeListener listener) {
8147         synchronized (getObjectLock()) {
8148             if (listener == null) {
8149                 return;
8150             }
8151             if (changeSupport == null) {
8152                 changeSupport = new PropertyChangeSupport(this);
8153             }
8154             changeSupport.addPropertyChangeListener(propertyName, listener);
8155         }
8156     }
8157 
8158     /**
8159      * Removes a <code>PropertyChangeListener</code> from the listener
8160      * list for a specific property. This method should be used to remove
8161      * <code>PropertyChangeListener</code>s
8162      * that were registered for a specific bound property.
8163      * <p>
8164      * If <code>propertyName</code> or <code>listener</code> is <code>null</code>,
8165      * no exception is thrown and no action is taken.
8166      *
8167      * @param propertyName a valid property name
8168      * @param listener the PropertyChangeListener to be removed
8169      *
8170      * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8171      * @see #getPropertyChangeListeners(java.lang.String)
8172      * @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
8173      */
8174     public void removePropertyChangeListener(
8175                                                           String propertyName,
8176                                                           PropertyChangeListener listener) {
8177         synchronized (getObjectLock()) {
8178             if (listener == null || changeSupport == null) {
8179                 return;
8180             }
8181             changeSupport.removePropertyChangeListener(propertyName, listener);
8182         }
8183     }
8184 
8185     /**
8186      * Returns an array of all the listeners which have been associated
8187      * with the named property.
8188      *
8189      * @return all of the <code>PropertyChangeListener</code>s associated with
8190      *         the named property; if no such listeners have been added or
8191      *         if <code>propertyName</code> is <code>null</code>, an empty
8192      *         array is returned
8193      *
8194      * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8195      * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8196      * @see #getPropertyChangeListeners
8197      * @since 1.4
8198      */
8199     public PropertyChangeListener[] getPropertyChangeListeners(
8200                                                                             String propertyName) {
8201         synchronized (getObjectLock()) {
8202             if (changeSupport == null) {
8203                 return new PropertyChangeListener[0];
8204             }
8205             return changeSupport.getPropertyChangeListeners(propertyName);
8206         }
8207     }
8208 
8209     /**
8210      * Support for reporting bound property changes for Object properties.
8211      * This method can be called when a bound property has changed and it will
8212      * send the appropriate PropertyChangeEvent to any registered
8213      * PropertyChangeListeners.
8214      *
8215      * @param propertyName the property whose value has changed
8216      * @param oldValue the property's previous value
8217      * @param newValue the property's new value
8218      */
8219     protected void firePropertyChange(String propertyName,
8220                                       Object oldValue, Object newValue) {
8221         PropertyChangeSupport changeSupport;
8222         synchronized (getObjectLock()) {
8223             changeSupport = this.changeSupport;
8224         }
8225         if (changeSupport == null ||
8226             (oldValue != null && newValue != null && oldValue.equals(newValue))) {
8227             return;
8228         }
8229         changeSupport.firePropertyChange(propertyName, oldValue, newValue);
8230     }
8231 
8232     /**
8233      * Support for reporting bound property changes for boolean properties.
8234      * This method can be called when a bound property has changed and it will
8235      * send the appropriate PropertyChangeEvent to any registered
8236      * PropertyChangeListeners.
8237      *
8238      * @param propertyName the property whose value has changed
8239      * @param oldValue the property's previous value
8240      * @param newValue the property's new value
8241      * @since 1.4
8242      */
8243     protected void firePropertyChange(String propertyName,
8244                                       boolean oldValue, boolean newValue) {
8245         PropertyChangeSupport changeSupport = this.changeSupport;
8246         if (changeSupport == null || oldValue == newValue) {
8247             return;
8248         }
8249         changeSupport.firePropertyChange(propertyName, oldValue, newValue);
8250     }
8251 
8252     /**
8253      * Support for reporting bound property changes for integer properties.
8254      * This method can be called when a bound property has changed and it will
8255      * send the appropriate PropertyChangeEvent to any registered
8256      * PropertyChangeListeners.
8257      *
8258      * @param propertyName the property whose value has changed
8259      * @param oldValue the property's previous value
8260      * @param newValue the property's new value
8261      * @since 1.4
8262      */
8263     protected void firePropertyChange(String propertyName,
8264                                       int oldValue, int newValue) {
8265         PropertyChangeSupport changeSupport = this.changeSupport;
8266         if (changeSupport == null || oldValue == newValue) {
8267             return;
8268         }
8269         changeSupport.firePropertyChange(propertyName, oldValue, newValue);
8270     }
8271 
8272     /**
8273      * Reports a bound property change.
8274      *
8275      * @param propertyName the programmatic name of the property
8276      *          that was changed
8277      * @param oldValue the old value of the property (as a byte)
8278      * @param newValue the new value of the property (as a byte)
8279      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8280      *          java.lang.Object)
8281      * @since 1.5
8282      */
8283     public void firePropertyChange(String propertyName, byte oldValue, byte newValue) {
8284         if (changeSupport == null || oldValue == newValue) {
8285             return;
8286         }
8287         firePropertyChange(propertyName, Byte.valueOf(oldValue), Byte.valueOf(newValue));
8288     }
8289 
8290     /**
8291      * Reports a bound property change.
8292      *
8293      * @param propertyName the programmatic name of the property
8294      *          that was changed
8295      * @param oldValue the old value of the property (as a char)
8296      * @param newValue the new value of the property (as a char)
8297      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8298      *          java.lang.Object)
8299      * @since 1.5
8300      */
8301     public void firePropertyChange(String propertyName, char oldValue, char newValue) {
8302         if (changeSupport == null || oldValue == newValue) {
8303             return;
8304         }
8305         firePropertyChange(propertyName, new Character(oldValue), new Character(newValue));
8306     }
8307 
8308     /**
8309      * Reports a bound property change.
8310      *
8311      * @param propertyName the programmatic name of the property
8312      *          that was changed
8313      * @param oldValue the old value of the property (as a short)
8314      * @param newValue the old value of the property (as a short)
8315      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8316      *          java.lang.Object)
8317      * @since 1.5
8318      */
8319     public void firePropertyChange(String propertyName, short oldValue, short newValue) {
8320         if (changeSupport == null || oldValue == newValue) {
8321             return;
8322         }
8323         firePropertyChange(propertyName, Short.valueOf(oldValue), Short.valueOf(newValue));
8324     }
8325 
8326 
8327     /**
8328      * Reports a bound property change.
8329      *
8330      * @param propertyName the programmatic name of the property
8331      *          that was changed
8332      * @param oldValue the old value of the property (as a long)
8333      * @param newValue the new value of the property (as a long)
8334      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8335      *          java.lang.Object)
8336      * @since 1.5
8337      */
8338     public void firePropertyChange(String propertyName, long oldValue, long newValue) {
8339         if (changeSupport == null || oldValue == newValue) {
8340             return;
8341         }
8342         firePropertyChange(propertyName, Long.valueOf(oldValue), Long.valueOf(newValue));
8343     }
8344 
8345     /**
8346      * Reports a bound property change.
8347      *
8348      * @param propertyName the programmatic name of the property
8349      *          that was changed
8350      * @param oldValue the old value of the property (as a float)
8351      * @param newValue the new value of the property (as a float)
8352      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8353      *          java.lang.Object)
8354      * @since 1.5
8355      */
8356     public void firePropertyChange(String propertyName, float oldValue, float newValue) {
8357         if (changeSupport == null || oldValue == newValue) {
8358             return;
8359         }
8360         firePropertyChange(propertyName, Float.valueOf(oldValue), Float.valueOf(newValue));
8361     }
8362 
8363     /**
8364      * Reports a bound property change.
8365      *
8366      * @param propertyName the programmatic name of the property
8367      *          that was changed
8368      * @param oldValue the old value of the property (as a double)
8369      * @param newValue the new value of the property (as a double)
8370      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8371      *          java.lang.Object)
8372      * @since 1.5
8373      */
8374     public void firePropertyChange(String propertyName, double oldValue, double newValue) {
8375         if (changeSupport == null || oldValue == newValue) {
8376             return;
8377         }
8378         firePropertyChange(propertyName, Double.valueOf(oldValue), Double.valueOf(newValue));
8379     }
8380 
8381 
8382     // Serialization support.
8383 
8384     /**
8385      * Component Serialized Data Version.
8386      *
8387      * @serial
8388      */
8389     private int componentSerializedDataVersion = 4;
8390 
8391     /**
8392      * This hack is for Swing serialization. It will invoke
8393      * the Swing package private method <code>compWriteObjectNotify</code>.
8394      */
8395     private void doSwingSerialization() {
8396         Package swingPackage = Package.getPackage("javax.swing");
8397         // For Swing serialization to correctly work Swing needs to
8398         // be notified before Component does it's serialization.  This
8399         // hack accomodates this.
8400         //
8401         // Swing classes MUST be loaded by the bootstrap class loader,
8402         // otherwise we don't consider them.
8403         for (Class klass = Component.this.getClass(); klass != null;
8404                    klass = klass.getSuperclass()) {
8405             if (klass.getPackage() == swingPackage &&
8406                       klass.getClassLoader() == null) {
8407                 final Class swingClass = klass;
8408                 // Find the first override of the compWriteObjectNotify method
8409                 Method[] methods = (Method[])AccessController.doPrivileged(
8410                                                                            new PrivilegedAction() {
8411                                                                                public Object run() {
8412                                                                                    return swingClass.getDeclaredMethods();
8413                                                                                }
8414                                                                            });
8415                 for (int counter = methods.length - 1; counter >= 0;
8416                      counter--) {
8417                     final Method method = methods[counter];
8418                     if (method.getName().equals("compWriteObjectNotify")){
8419                         // We found it, use doPrivileged to make it accessible
8420                         // to use.
8421                         AccessController.doPrivileged(new PrivilegedAction() {
8422                                 public Object run() {
8423                                     method.setAccessible(true);
8424                                     return null;
8425                                 }
8426                             });
8427                         // Invoke the method
8428                         try {
8429                             method.invoke(this, (Object[]) null);
8430                         } catch (IllegalAccessException iae) {
8431                         } catch (InvocationTargetException ite) {
8432                         }
8433                         // We're done, bail.
8434                         return;
8435                     }
8436                 }
8437             }
8438         }
8439     }
8440 
8441     /**
8442      * Writes default serializable fields to stream.  Writes
8443      * a variety of serializable listeners as optional data.
8444      * The non-serializable listeners are detected and
8445      * no attempt is made to serialize them.
8446      *
8447      * @param s the <code>ObjectOutputStream</code> to write
8448      * @serialData <code>null</code> terminated sequence of
8449      *   0 or more pairs; the pair consists of a <code>String</code>
8450      *   and an <code>Object</code>; the <code>String</code> indicates
8451      *   the type of object and is one of the following (as of 1.4):
8452      *   <code>componentListenerK</code> indicating an
8453      *     <code>ComponentListener</code> object;
8454      *   <code>focusListenerK</code> indicating an
8455      *     <code>FocusListener</code> object;
8456      *   <code>keyListenerK</code> indicating an
8457      *     <code>KeyListener</code> object;
8458      *   <code>mouseListenerK</code> indicating an
8459      *     <code>MouseListener</code> object;
8460      *   <code>mouseMotionListenerK</code> indicating an
8461      *     <code>MouseMotionListener</code> object;
8462      *   <code>inputMethodListenerK</code> indicating an
8463      *     <code>InputMethodListener</code> object;
8464      *   <code>hierarchyListenerK</code> indicating an
8465      *     <code>HierarchyListener</code> object;
8466      *   <code>hierarchyBoundsListenerK</code> indicating an
8467      *     <code>HierarchyBoundsListener</code> object;
8468      *   <code>mouseWheelListenerK</code> indicating an
8469      *     <code>MouseWheelListener</code> object
8470      * @serialData an optional <code>ComponentOrientation</code>
8471      *    (after <code>inputMethodListener</code>, as of 1.2)
8472      *
8473      * @see AWTEventMulticaster#save(java.io.ObjectOutputStream, java.lang.String, java.util.EventListener)
8474      * @see #componentListenerK
8475      * @see #focusListenerK
8476      * @see #keyListenerK
8477      * @see #mouseListenerK
8478      * @see #mouseMotionListenerK
8479      * @see #inputMethodListenerK
8480      * @see #hierarchyListenerK
8481      * @see #hierarchyBoundsListenerK
8482      * @see #mouseWheelListenerK
8483      * @see #readObject(ObjectInputStream)
8484      */
8485     private void writeObject(ObjectOutputStream s)
8486       throws IOException
8487     {
8488         doSwingSerialization();
8489 
8490         s.defaultWriteObject();
8491 
8492         AWTEventMulticaster.save(s, componentListenerK, componentListener);
8493         AWTEventMulticaster.save(s, focusListenerK, focusListener);
8494         AWTEventMulticaster.save(s, keyListenerK, keyListener);
8495         AWTEventMulticaster.save(s, mouseListenerK, mouseListener);
8496         AWTEventMulticaster.save(s, mouseMotionListenerK, mouseMotionListener);
8497         AWTEventMulticaster.save(s, inputMethodListenerK, inputMethodListener);
8498 
8499         s.writeObject(null);
8500         s.writeObject(componentOrientation);
8501 
8502         AWTEventMulticaster.save(s, hierarchyListenerK, hierarchyListener);
8503         AWTEventMulticaster.save(s, hierarchyBoundsListenerK,
8504                                  hierarchyBoundsListener);
8505         s.writeObject(null);
8506 
8507         AWTEventMulticaster.save(s, mouseWheelListenerK, mouseWheelListener);
8508         s.writeObject(null);
8509 
8510     }
8511 
8512     /**
8513      * Reads the <code>ObjectInputStream</code> and if it isn't
8514      * <code>null</code> adds a listener to receive a variety
8515      * of events fired by the component.
8516      * Unrecognized keys or values will be ignored.
8517      *
8518      * @param s the <code>ObjectInputStream</code> to read
8519      * @see #writeObject(ObjectOutputStream)
8520      */
8521     private void readObject(ObjectInputStream s)
8522       throws ClassNotFoundException, IOException
8523     {
8524         objectLock = new Object();
8525 
8526         s.defaultReadObject();
8527 
8528         appContext = AppContext.getAppContext();
8529         coalescingEnabled = checkCoalescing();
8530         if (componentSerializedDataVersion < 4) {
8531             // These fields are non-transient and rely on default
8532             // serialization. However, the default values are insufficient,
8533             // so we need to set them explicitly for object data streams prior
8534             // to 1.4.
8535             focusable = true;
8536             isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN;
8537             initializeFocusTraversalKeys();
8538             focusTraversalKeysEnabled = true;
8539         }
8540 
8541         Object keyOrNull;
8542         while(null != (keyOrNull = s.readObject())) {
8543             String key = ((String)keyOrNull).intern();
8544 
8545             if (componentListenerK == key)
8546                 addComponentListener((ComponentListener)(s.readObject()));
8547 
8548             else if (focusListenerK == key)
8549                 addFocusListener((FocusListener)(s.readObject()));
8550 
8551             else if (keyListenerK == key)
8552                 addKeyListener((KeyListener)(s.readObject()));
8553 
8554             else if (mouseListenerK == key)
8555                 addMouseListener((MouseListener)(s.readObject()));
8556 
8557             else if (mouseMotionListenerK == key)
8558                 addMouseMotionListener((MouseMotionListener)(s.readObject()));
8559 
8560             else if (inputMethodListenerK == key)
8561                 addInputMethodListener((InputMethodListener)(s.readObject()));
8562 
8563             else // skip value for unrecognized key
8564                 s.readObject();
8565 
8566         }
8567 
8568         // Read the component's orientation if it's present
8569         Object orient = null;
8570 
8571         try {
8572             orient = s.readObject();
8573         } catch (java.io.OptionalDataException e) {
8574             // JDK 1.1 instances will not have this optional data.
8575             // e.eof will be true to indicate that there is no more
8576             // data available for this object.
8577             // If e.eof is not true, throw the exception as it
8578             // might have been caused by reasons unrelated to
8579             // componentOrientation.
8580 
8581             if (!e.eof)  {
8582                 throw (e);
8583             }
8584         }
8585 
8586         if (orient != null) {
8587             componentOrientation = (ComponentOrientation)orient;
8588         } else {
8589             componentOrientation = ComponentOrientation.UNKNOWN;
8590         }
8591 
8592         try {
8593             while(null != (keyOrNull = s.readObject())) {
8594                 String key = ((String)keyOrNull).intern();
8595 
8596                 if (hierarchyListenerK == key) {
8597                     addHierarchyListener((HierarchyListener)(s.readObject()));
8598                 }
8599                 else if (hierarchyBoundsListenerK == key) {
8600                     addHierarchyBoundsListener((HierarchyBoundsListener)
8601                                                (s.readObject()));
8602                 }
8603                 else {
8604                     // skip value for unrecognized key
8605                     s.readObject();
8606                 }
8607             }
8608         } catch (java.io.OptionalDataException e) {
8609             // JDK 1.1/1.2 instances will not have this optional data.
8610             // e.eof will be true to indicate that there is no more
8611             // data available for this object.
8612             // If e.eof is not true, throw the exception as it
8613             // might have been caused by reasons unrelated to
8614             // hierarchy and hierarchyBounds listeners.
8615 
8616             if (!e.eof)  {
8617                 throw (e);
8618             }
8619         }
8620 
8621         try {
8622             while (null != (keyOrNull = s.readObject())) {
8623                 String key = ((String)keyOrNull).intern();
8624 
8625                 if (mouseWheelListenerK == key) {
8626                     addMouseWheelListener((MouseWheelListener)(s.readObject()));
8627                 }
8628                 else {
8629                     // skip value for unrecognized key
8630                     s.readObject();
8631                 }
8632             }
8633         } catch (java.io.OptionalDataException e) {
8634             // pre-1.3 instances will not have this optional data.
8635             // e.eof will be true to indicate that there is no more
8636             // data available for this object.
8637             // If e.eof is not true, throw the exception as it
8638             // might have been caused by reasons unrelated to
8639             // mouse wheel listeners
8640 
8641             if (!e.eof)  {
8642                 throw (e);
8643             }
8644         }
8645 
8646         if (popups != null) {
8647             int npopups = popups.size();
8648             for (int i = 0 ; i < npopups ; i++) {
8649                 PopupMenu popup = (PopupMenu)popups.elementAt(i);
8650                 popup.parent = this;
8651             }
8652         }
8653     }
8654 
8655     /**
8656      * Sets the language-sensitive orientation that is to be used to order
8657      * the elements or text within this component.  Language-sensitive
8658      * <code>LayoutManager</code> and <code>Component</code>
8659      * subclasses will use this property to
8660      * determine how to lay out and draw components.
8661      * <p>
8662      * At construction time, a component's orientation is set to
8663      * <code>ComponentOrientation.UNKNOWN</code>,
8664      * indicating that it has not been specified
8665      * explicitly.  The UNKNOWN orientation behaves the same as
8666      * <code>ComponentOrientation.LEFT_TO_RIGHT</code>.
8667      * <p>
8668      * To set the orientation of a single component, use this method.
8669      * To set the orientation of an entire component
8670      * hierarchy, use
8671      * {@link #applyComponentOrientation applyComponentOrientation}.
8672      * <p>
8673      * This method changes layout-related information, and therefore,
8674      * invalidates the component hierarchy.
8675      *
8676      *
8677      * @see ComponentOrientation
8678      * @see #invalidate
8679      *
8680      * @author Laura Werner, IBM
8681      * @beaninfo
8682      *       bound: true
8683      */
8684     public void setComponentOrientation(ComponentOrientation o) {
8685         ComponentOrientation oldValue = componentOrientation;
8686         componentOrientation = o;
8687 
8688         // This is a bound property, so report the change to
8689         // any registered listeners.  (Cheap if there are none.)
8690         firePropertyChange("componentOrientation", oldValue, o);
8691 
8692         // This could change the preferred size of the Component.
8693         invalidateIfValid();
8694     }
8695 
8696     /**
8697      * Retrieves the language-sensitive orientation that is to be used to order
8698      * the elements or text within this component.  <code>LayoutManager</code>
8699      * and <code>Component</code>
8700      * subclasses that wish to respect orientation should call this method to
8701      * get the component's orientation before performing layout or drawing.
8702      *
8703      * @see ComponentOrientation
8704      *
8705      * @author Laura Werner, IBM
8706      */
8707     public ComponentOrientation getComponentOrientation() {
8708         return componentOrientation;
8709     }
8710 
8711     /**
8712      * Sets the <code>ComponentOrientation</code> property of this component
8713      * and all components contained within it.
8714      * <p>
8715      * This method changes layout-related information, and therefore,
8716      * invalidates the component hierarchy.
8717      *
8718      *
8719      * @param orientation the new component orientation of this component and
8720      *        the components contained within it.
8721      * @exception NullPointerException if <code>orientation</code> is null.
8722      * @see #setComponentOrientation
8723      * @see #getComponentOrientation
8724      * @see #invalidate
8725      * @since 1.4
8726      */
8727     public void applyComponentOrientation(ComponentOrientation orientation) {
8728         if (orientation == null) {
8729             throw new NullPointerException();
8730         }
8731         setComponentOrientation(orientation);
8732     }
8733 
8734     final boolean canBeFocusOwner() {
8735         // It is enabled, visible, focusable.
8736         if (isEnabled() && isDisplayable() && isVisible() && isFocusable()) {
8737             return true;
8738         }
8739         return false;
8740     }
8741 
8742     /**
8743      * Checks that this component meets the prerequesites to be focus owner:
8744      * - it is enabled, visible, focusable
8745      * - it's parents are all enabled and showing
8746      * - top-level window is focusable
8747      * - if focus cycle root has DefaultFocusTraversalPolicy then it also checks that this policy accepts
8748      * this component as focus owner
8749      * @since 1.5
8750      */
8751     final boolean canBeFocusOwnerRecursively() {
8752         // - it is enabled, visible, focusable
8753         if (!canBeFocusOwner()) {
8754             return false;
8755         }
8756 
8757         // - it's parents are all enabled and showing
8758         synchronized(getTreeLock()) {
8759             if (parent != null) {
8760                 return parent.canContainFocusOwner(this);
8761             }
8762         }
8763         return true;
8764     }
8765 
8766     /**
8767      * Fix the location of the HW component in a LW container hierarchy.
8768      */
8769     final void relocateComponent() {
8770         synchronized (getTreeLock()) {
8771             if (peer == null) {
8772                 return;
8773             }
8774             int nativeX = x;
8775             int nativeY = y;
8776             for (Component cont = getContainer();
8777                     cont != null && cont.isLightweight();
8778                     cont = cont.getContainer())
8779             {
8780                 nativeX += cont.x;
8781                 nativeY += cont.y;
8782             }
8783             peer.setBounds(nativeX, nativeY, width, height,
8784                     ComponentPeer.SET_LOCATION);
8785         }
8786     }
8787 
8788     /**
8789      * Returns the <code>Window</code> ancestor of the component.
8790      * @return Window ancestor of the component or component by itself if it is Window;
8791      *         null, if component is not a part of window hierarchy
8792      */
8793     Window getContainingWindow() {
8794         return SunToolkit.getContainingWindow(this);
8795     }
8796 
8797     /**
8798      * Initialize JNI field and method IDs
8799      */
8800     private static native void initIDs();
8801 
8802     /*
8803      * --- Accessibility Support ---
8804      *
8805      *  Component will contain all of the methods in interface Accessible,
8806      *  though it won't actually implement the interface - that will be up
8807      *  to the individual objects which extend Component.
8808      */
8809 
8810     AccessibleContext accessibleContext = null;
8811 
8812     /**
8813      * Gets the <code>AccessibleContext</code> associated
8814      * with this <code>Component</code>.
8815      * The method implemented by this base
8816      * class returns null.  Classes that extend <code>Component</code>
8817      * should implement this method to return the
8818      * <code>AccessibleContext</code> associated with the subclass.
8819      *
8820      *
8821      * @return the <code>AccessibleContext</code> of this
8822      *    <code>Component</code>
8823      * @since 1.3
8824      */
8825     public AccessibleContext getAccessibleContext() {
8826         return accessibleContext;
8827     }
8828 
8829     /**
8830      * Inner class of Component used to provide default support for
8831      * accessibility.  This class is not meant to be used directly by
8832      * application developers, but is instead meant only to be
8833      * subclassed by component developers.
8834      * <p>
8835      * The class used to obtain the accessible role for this object.
8836      * @since 1.3
8837      */
8838     protected abstract class AccessibleAWTComponent extends AccessibleContext
8839         implements Serializable, AccessibleComponent {
8840 
8841         private static final long serialVersionUID = 642321655757800191L;
8842 
8843         /**
8844          * Though the class is abstract, this should be called by
8845          * all sub-classes.
8846          */
8847         protected AccessibleAWTComponent() {
8848         }
8849 
8850         protected ComponentListener accessibleAWTComponentHandler = null;
8851         protected FocusListener accessibleAWTFocusHandler = null;
8852 
8853         /**
8854          * Fire PropertyChange listener, if one is registered,
8855          * when shown/hidden..
8856          * @since 1.3
8857          */
8858         protected class AccessibleAWTComponentHandler implements ComponentListener {
8859             public void componentHidden(ComponentEvent e)  {
8860                 if (accessibleContext != null) {
8861                     accessibleContext.firePropertyChange(
8862                                                          AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
8863                                                          AccessibleState.VISIBLE, null);
8864                 }
8865             }
8866 
8867             public void componentShown(ComponentEvent e)  {
8868                 if (accessibleContext != null) {
8869                     accessibleContext.firePropertyChange(
8870                                                          AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
8871                                                          null, AccessibleState.VISIBLE);
8872                 }
8873             }
8874 
8875             public void componentMoved(ComponentEvent e)  {
8876             }
8877 
8878             public void componentResized(ComponentEvent e)  {
8879             }
8880         } // inner class AccessibleAWTComponentHandler
8881 
8882 
8883         /**
8884          * Fire PropertyChange listener, if one is registered,
8885          * when focus events happen
8886          * @since 1.3
8887          */
8888         protected class AccessibleAWTFocusHandler implements FocusListener {
8889             public void focusGained(FocusEvent event) {
8890                 if (accessibleContext != null) {
8891                     accessibleContext.firePropertyChange(
8892                                                          AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
8893                                                          null, AccessibleState.FOCUSED);
8894                 }
8895             }
8896             public void focusLost(FocusEvent event) {
8897                 if (accessibleContext != null) {
8898                     accessibleContext.firePropertyChange(
8899                                                          AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
8900                                                          AccessibleState.FOCUSED, null);
8901                 }
8902             }
8903         }  // inner class AccessibleAWTFocusHandler
8904 
8905 
8906         /**
8907          * Adds a <code>PropertyChangeListener</code> to the listener list.
8908          *
8909          * @param listener  the property change listener to be added
8910          */
8911         public void addPropertyChangeListener(PropertyChangeListener listener) {
8912             if (accessibleAWTComponentHandler == null) {
8913                 accessibleAWTComponentHandler = new AccessibleAWTComponentHandler();
8914                 Component.this.addComponentListener(accessibleAWTComponentHandler);
8915             }
8916             if (accessibleAWTFocusHandler == null) {
8917                 accessibleAWTFocusHandler = new AccessibleAWTFocusHandler();
8918                 Component.this.addFocusListener(accessibleAWTFocusHandler);
8919             }
8920             super.addPropertyChangeListener(listener);
8921         }
8922 
8923         /**
8924          * Remove a PropertyChangeListener from the listener list.
8925          * This removes a PropertyChangeListener that was registered
8926          * for all properties.
8927          *
8928          * @param listener  The PropertyChangeListener to be removed
8929          */
8930         public void removePropertyChangeListener(PropertyChangeListener listener) {
8931             if (accessibleAWTComponentHandler != null) {
8932                 Component.this.removeComponentListener(accessibleAWTComponentHandler);
8933                 accessibleAWTComponentHandler = null;
8934             }
8935             if (accessibleAWTFocusHandler != null) {
8936                 Component.this.removeFocusListener(accessibleAWTFocusHandler);
8937                 accessibleAWTFocusHandler = null;
8938             }
8939             super.removePropertyChangeListener(listener);
8940         }
8941 
8942         // AccessibleContext methods
8943         //
8944         /**
8945          * Gets the accessible name of this object.  This should almost never
8946          * return <code>java.awt.Component.getName()</code>,
8947          * as that generally isn't a localized name,
8948          * and doesn't have meaning for the user.  If the
8949          * object is fundamentally a text object (e.g. a menu item), the
8950          * accessible name should be the text of the object (e.g. "save").
8951          * If the object has a tooltip, the tooltip text may also be an
8952          * appropriate String to return.
8953          *
8954          * @return the localized name of the object -- can be
8955          *         <code>null</code> if this
8956          *         object does not have a name
8957          * @see javax.accessibility.AccessibleContext#setAccessibleName
8958          */
8959         public String getAccessibleName() {
8960             return accessibleName;
8961         }
8962 
8963         /**
8964          * Gets the accessible description of this object.  This should be
8965          * a concise, localized description of what this object is - what
8966          * is its meaning to the user.  If the object has a tooltip, the
8967          * tooltip text may be an appropriate string to return, assuming
8968          * it contains a concise description of the object (instead of just
8969          * the name of the object - e.g. a "Save" icon on a toolbar that
8970          * had "save" as the tooltip text shouldn't return the tooltip
8971          * text as the description, but something like "Saves the current
8972          * text document" instead).
8973          *
8974          * @return the localized description of the object -- can be
8975          *        <code>null</code> if this object does not have a description
8976          * @see javax.accessibility.AccessibleContext#setAccessibleDescription
8977          */
8978         public String getAccessibleDescription() {
8979             return accessibleDescription;
8980         }
8981 
8982         /**
8983          * Gets the role of this object.
8984          *
8985          * @return an instance of <code>AccessibleRole</code>
8986          *      describing the role of the object
8987          * @see javax.accessibility.AccessibleRole
8988          */
8989         public AccessibleRole getAccessibleRole() {
8990             return AccessibleRole.AWT_COMPONENT;
8991         }
8992 
8993         /**
8994          * Gets the state of this object.
8995          *
8996          * @return an instance of <code>AccessibleStateSet</code>
8997          *       containing the current state set of the object
8998          * @see javax.accessibility.AccessibleState
8999          */
9000         public AccessibleStateSet getAccessibleStateSet() {
9001             return Component.this.getAccessibleStateSet();
9002         }
9003 
9004         /**
9005          * Gets the <code>Accessible</code> parent of this object.
9006          * If the parent of this object implements <code>Accessible</code>,
9007          * this method should simply return <code>getParent</code>.
9008          *
9009          * @return the <code>Accessible</code> parent of this
9010          *      object -- can be <code>null</code> if this
9011          *      object does not have an <code>Accessible</code> parent
9012          */
9013         public Accessible getAccessibleParent() {
9014             if (accessibleParent != null) {
9015                 return accessibleParent;
9016             } else {
9017                 Container parent = getParent();
9018                 if (parent instanceof Accessible) {
9019                     return (Accessible) parent;
9020                 }
9021             }
9022             return null;
9023         }
9024 
9025         /**
9026          * Gets the index of this object in its accessible parent.
9027          *
9028          * @return the index of this object in its parent; or -1 if this
9029          *    object does not have an accessible parent
9030          * @see #getAccessibleParent
9031          */
9032         public int getAccessibleIndexInParent() {
9033             return Component.this.getAccessibleIndexInParent();
9034         }
9035 
9036         /**
9037          * Returns the number of accessible children in the object.  If all
9038          * of the children of this object implement <code>Accessible</code>,
9039          * then this method should return the number of children of this object.
9040          *
9041          * @return the number of accessible children in the object
9042          */
9043         public int getAccessibleChildrenCount() {
9044             return 0; // Components don't have children
9045         }
9046 
9047         /**
9048          * Returns the nth <code>Accessible</code> child of the object.
9049          *
9050          * @param i zero-based index of child
9051          * @return the nth <code>Accessible</code> child of the object
9052          */
9053         public Accessible getAccessibleChild(int i) {
9054             return null; // Components don't have children
9055         }
9056 
9057         /**
9058          * Returns the locale of this object.
9059          *
9060          * @return the locale of this object
9061          */
9062         public Locale getLocale() {
9063             return Component.this.getLocale();
9064         }
9065 
9066         /**
9067          * Gets the <code>AccessibleComponent</code> associated
9068          * with this object if one exists.
9069          * Otherwise return <code>null</code>.
9070          *
9071          * @return the component
9072          */
9073         public AccessibleComponent getAccessibleComponent() {
9074             return this;
9075         }
9076 
9077 
9078         // AccessibleComponent methods
9079         //
9080         /**
9081          * Gets the background color of this object.
9082          *
9083          * @return the background color, if supported, of the object;
9084          *      otherwise, <code>null</code>
9085          */
9086         public Color getBackground() {
9087             return Component.this.getBackground();
9088         }
9089 
9090         /**
9091          * Sets the background color of this object.
9092          * (For transparency, see <code>isOpaque</code>.)
9093          *
9094          * @param c the new <code>Color</code> for the background
9095          * @see Component#isOpaque
9096          */
9097         public void setBackground(Color c) {
9098             Component.this.setBackground(c);
9099         }
9100 
9101         /**
9102          * Gets the foreground color of this object.
9103          *
9104          * @return the foreground color, if supported, of the object;
9105          *     otherwise, <code>null</code>
9106          */
9107         public Color getForeground() {
9108             return Component.this.getForeground();
9109         }
9110 
9111         /**
9112          * Sets the foreground color of this object.
9113          *
9114          * @param c the new <code>Color</code> for the foreground
9115          */
9116         public void setForeground(Color c) {
9117             Component.this.setForeground(c);
9118         }
9119 
9120         /**
9121          * Gets the <code>Cursor</code> of this object.
9122          *
9123          * @return the <code>Cursor</code>, if supported,
9124          *     of the object; otherwise, <code>null</code>
9125          */
9126         public Cursor getCursor() {
9127             return Component.this.getCursor();
9128         }
9129 
9130         /**
9131          * Sets the <code>Cursor</code> of this object.
9132          * <p>
9133          * The method may have no visual effect if the Java platform
9134          * implementation and/or the native system do not support
9135          * changing the mouse cursor shape.
9136          * @param cursor the new <code>Cursor</code> for the object
9137          */
9138         public void setCursor(Cursor cursor) {
9139             Component.this.setCursor(cursor);
9140         }
9141 
9142         /**
9143          * Gets the <code>Font</code> of this object.
9144          *
9145          * @return the <code>Font</code>, if supported,
9146          *    for the object; otherwise, <code>null</code>
9147          */
9148         public Font getFont() {
9149             return Component.this.getFont();
9150         }
9151 
9152         /**
9153          * Sets the <code>Font</code> of this object.
9154          *
9155          * @param f the new <code>Font</code> for the object
9156          */
9157         public void setFont(Font f) {
9158             Component.this.setFont(f);
9159         }
9160 
9161         /**
9162          * Gets the <code>FontMetrics</code> of this object.
9163          *
9164          * @param f the <code>Font</code>
9165          * @return the <code>FontMetrics</code>, if supported,
9166          *     the object; otherwise, <code>null</code>
9167          * @see #getFont
9168          */
9169         public FontMetrics getFontMetrics(Font f) {
9170             if (f == null) {
9171                 return null;
9172             } else {
9173                 return Component.this.getFontMetrics(f);
9174             }
9175         }
9176 
9177         /**
9178          * Determines if the object is enabled.
9179          *
9180          * @return true if object is enabled; otherwise, false
9181          */
9182         public boolean isEnabled() {
9183             return Component.this.isEnabled();
9184         }
9185 
9186         /**
9187          * Sets the enabled state of the object.
9188          *
9189          * @param b if true, enables this object; otherwise, disables it
9190          */
9191         public void setEnabled(boolean b) {
9192             boolean old = Component.this.isEnabled();
9193             Component.this.setEnabled(b);
9194             if (b != old) {
9195                 if (accessibleContext != null) {
9196                     if (b) {
9197                         accessibleContext.firePropertyChange(
9198                                                              AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9199                                                              null, AccessibleState.ENABLED);
9200                     } else {
9201                         accessibleContext.firePropertyChange(
9202                                                              AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9203                                                              AccessibleState.ENABLED, null);
9204                     }
9205                 }
9206             }
9207         }
9208 
9209         /**
9210          * Determines if the object is visible.  Note: this means that the
9211          * object intends to be visible; however, it may not in fact be
9212          * showing on the screen because one of the objects that this object
9213          * is contained by is not visible.  To determine if an object is
9214          * showing on the screen, use <code>isShowing</code>.
9215          *
9216          * @return true if object is visible; otherwise, false
9217          */
9218         public boolean isVisible() {
9219             return Component.this.isVisible();
9220         }
9221 
9222         /**
9223          * Sets the visible state of the object.
9224          *
9225          * @param b if true, shows this object; otherwise, hides it
9226          */
9227         public void setVisible(boolean b) {
9228             boolean old = Component.this.isVisible();
9229             Component.this.setVisible(b);
9230             if (b != old) {
9231                 if (accessibleContext != null) {
9232                     if (b) {
9233                         accessibleContext.firePropertyChange(
9234                                                              AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9235                                                              null, AccessibleState.VISIBLE);
9236                     } else {
9237                         accessibleContext.firePropertyChange(
9238                                                              AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9239                                                              AccessibleState.VISIBLE, null);
9240                     }
9241                 }
9242             }
9243         }
9244 
9245         /**
9246          * Determines if the object is showing.  This is determined by checking
9247          * the visibility of the object and ancestors of the object.  Note:
9248          * this will return true even if the object is obscured by another
9249          * (for example, it happens to be underneath a menu that was pulled
9250          * down).
9251          *
9252          * @return true if object is showing; otherwise, false
9253          */
9254         public boolean isShowing() {
9255             return Component.this.isShowing();
9256         }
9257 
9258         /**
9259          * Checks whether the specified point is within this object's bounds,
9260          * where the point's x and y coordinates are defined to be relative to
9261          * the coordinate system of the object.
9262          *
9263          * @param p the <code>Point</code> relative to the
9264          *     coordinate system of the object
9265          * @return true if object contains <code>Point</code>; otherwise false
9266          */
9267         public boolean contains(Point p) {
9268             return Component.this.contains(p);
9269         }
9270 
9271         /**
9272          * Returns the location of the object on the screen.
9273          *
9274          * @return location of object on screen -- can be
9275          *    <code>null</code> if this object is not on the screen
9276          */
9277         public Point getLocationOnScreen() {
9278             synchronized (Component.this.getTreeLock()) {
9279                 if (Component.this.isShowing()) {
9280                     return Component.this.getLocationOnScreen();
9281                 } else {
9282                     return null;
9283                 }
9284             }
9285         }
9286 
9287         /**
9288          * Gets the location of the object relative to the parent in the form
9289          * of a point specifying the object's top-left corner in the screen's
9290          * coordinate space.
9291          *
9292          * @return an instance of Point representing the top-left corner of
9293          * the object's bounds in the coordinate space of the screen;
9294          * <code>null</code> if this object or its parent are not on the screen
9295          */
9296         public Point getLocation() {
9297             return Component.this.getLocation();
9298         }
9299 
9300         /**
9301          * Sets the location of the object relative to the parent.
9302          * @param p  the coordinates of the object
9303          */
9304         public void setLocation(Point p) {
9305             Component.this.setLocation(p);
9306         }
9307 
9308         /**
9309          * Gets the bounds of this object in the form of a Rectangle object.
9310          * The bounds specify this object's width, height, and location
9311          * relative to its parent.
9312          *
9313          * @return a rectangle indicating this component's bounds;
9314          *   <code>null</code> if this object is not on the screen
9315          */
9316         public Rectangle getBounds() {
9317             return Component.this.getBounds();
9318         }
9319 
9320         /**
9321          * Sets the bounds of this object in the form of a
9322          * <code>Rectangle</code> object.
9323          * The bounds specify this object's width, height, and location
9324          * relative to its parent.
9325          *
9326          * @param r a rectangle indicating this component's bounds
9327          */
9328         public void setBounds(Rectangle r) {
9329             Component.this.setBounds(r);
9330         }
9331 
9332         /**
9333          * Returns the size of this object in the form of a
9334          * <code>Dimension</code> object. The height field of the
9335          * <code>Dimension</code> object contains this objects's
9336          * height, and the width field of the <code>Dimension</code>
9337          * object contains this object's width.
9338          *
9339          * @return a <code>Dimension</code> object that indicates
9340          *     the size of this component; <code>null</code> if
9341          *     this object is not on the screen
9342          */
9343         public Dimension getSize() {
9344             return Component.this.getSize();
9345         }
9346 
9347         /**
9348          * Resizes this object so that it has width and height.
9349          *
9350          * @param d - the dimension specifying the new size of the object
9351          */
9352         public void setSize(Dimension d) {
9353             Component.this.setSize(d);
9354         }
9355 
9356         /**
9357          * Returns the <code>Accessible</code> child,
9358          * if one exists, contained at the local
9359          * coordinate <code>Point</code>.  Otherwise returns
9360          * <code>null</code>.
9361          *
9362          * @param p the point defining the top-left corner of
9363          *      the <code>Accessible</code>, given in the
9364          *      coordinate space of the object's parent
9365          * @return the <code>Accessible</code>, if it exists,
9366          *      at the specified location; else <code>null</code>
9367          */
9368         public Accessible getAccessibleAt(Point p) {
9369             return null; // Components don't have children
9370         }
9371 
9372         /**
9373          * Returns whether this object can accept focus or not.
9374          *
9375          * @return true if object can accept focus; otherwise false
9376          */
9377         public boolean isFocusTraversable() {
9378             return Component.this.isFocusTraversable();
9379         }
9380 
9381         /**
9382          * Requests focus for this object.
9383          */
9384         public void requestFocus() {
9385             Component.this.requestFocus();
9386         }
9387 
9388         /**
9389          * Adds the specified focus listener to receive focus events from this
9390          * component.
9391          *
9392          * @param l the focus listener
9393          */
9394         public void addFocusListener(FocusListener l) {
9395             Component.this.addFocusListener(l);
9396         }
9397 
9398         /**
9399          * Removes the specified focus listener so it no longer receives focus
9400          * events from this component.
9401          *
9402          * @param l the focus listener
9403          */
9404         public void removeFocusListener(FocusListener l) {
9405             Component.this.removeFocusListener(l);
9406         }
9407 
9408     } // inner class AccessibleAWTComponent
9409 
9410 
9411     /**
9412      * Gets the index of this object in its accessible parent.
9413      * If this object does not have an accessible parent, returns
9414      * -1.
9415      *
9416      * @return the index of this object in its accessible parent
9417      */
9418     int getAccessibleIndexInParent() {
9419         synchronized (getTreeLock()) {
9420             int index = -1;
9421             Container parent = this.getParent();
9422             if (parent != null && parent instanceof Accessible) {
9423                 Component ca[] = parent.getComponents();
9424                 for (int i = 0; i < ca.length; i++) {
9425                     if (ca[i] instanceof Accessible) {
9426                         index++;
9427                     }
9428                     if (this.equals(ca[i])) {
9429                         return index;
9430                     }
9431                 }
9432             }
9433             return -1;
9434         }
9435     }
9436 
9437     /**
9438      * Gets the current state set of this object.
9439      *
9440      * @return an instance of <code>AccessibleStateSet</code>
9441      *    containing the current state set of the object
9442      * @see AccessibleState
9443      */
9444     AccessibleStateSet getAccessibleStateSet() {
9445         synchronized (getTreeLock()) {
9446             AccessibleStateSet states = new AccessibleStateSet();
9447             if (this.isEnabled()) {
9448                 states.add(AccessibleState.ENABLED);
9449             }
9450             if (this.isFocusTraversable()) {
9451                 states.add(AccessibleState.FOCUSABLE);
9452             }
9453             if (this.isVisible()) {
9454                 states.add(AccessibleState.VISIBLE);
9455             }
9456             if (this.isShowing()) {
9457                 states.add(AccessibleState.SHOWING);
9458             }
9459             if (this.isFocusOwner()) {
9460                 states.add(AccessibleState.FOCUSED);
9461             }
9462             if (this instanceof Accessible) {
9463                 AccessibleContext ac = ((Accessible) this).getAccessibleContext();
9464                 if (ac != null) {
9465                     Accessible ap = ac.getAccessibleParent();
9466                     if (ap != null) {
9467                         AccessibleContext pac = ap.getAccessibleContext();
9468                         if (pac != null) {
9469                             AccessibleSelection as = pac.getAccessibleSelection();
9470                             if (as != null) {
9471                                 states.add(AccessibleState.SELECTABLE);
9472                                 int i = ac.getAccessibleIndexInParent();
9473                                 if (i >= 0) {
9474                                     if (as.isAccessibleChildSelected(i)) {
9475                                         states.add(AccessibleState.SELECTED);
9476                                     }
9477                                 }
9478                             }
9479                         }
9480                     }
9481                 }
9482             }
9483             if (Component.isInstanceOf(this, "javax.swing.JComponent")) {
9484                 if (((javax.swing.JComponent) this).isOpaque()) {
9485                     states.add(AccessibleState.OPAQUE);
9486                 }
9487             }
9488             return states;
9489         }
9490     }
9491 
9492     /**
9493      * Checks that the given object is instance of the given class.
9494      * @param obj Object to be checked
9495      * @param className The name of the class. Must be fully-qualified class name.
9496      * @return true, if this object is instanceof given class,
9497      *         false, otherwise, or if obj or className is null
9498      */
9499     static boolean isInstanceOf(Object obj, String className) {
9500         if (obj == null) return false;
9501         if (className == null) return false;
9502 
9503         Class cls = obj.getClass();
9504         while (cls != null) {
9505             if (cls.getName().equals(className)) {
9506                 return true;
9507             }
9508             cls = cls.getSuperclass();
9509         }
9510         return false;
9511     }
9512 
9513 
9514     // ************************** MIXING CODE *******************************
9515 
9516     /**
9517      * Check whether we can trust the current bounds of the component.
9518      * The return value of false indicates that the container of the
9519      * component is invalid, and therefore needs to be layed out, which would
9520      * probably mean changing the bounds of its children.
9521      * Null-layout of the container or absence of the container mean
9522      * the bounds of the component are final and can be trusted.
9523      */
9524     final boolean areBoundsValid() {
9525         Container cont = getContainer();
9526         return cont == null || cont.isValid() || cont.getLayout() == null;
9527     }
9528 
9529     /**
9530      * Applies the shape to the component
9531      * @param shape Shape to be applied to the component
9532      */
9533     void applyCompoundShape(Region shape) {
9534         checkTreeLock();
9535 
9536         if (!areBoundsValid()) {
9537             if (mixingLog.isLoggable(Level.FINE)) {
9538                 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid());
9539             }
9540             return;
9541         }
9542 
9543         if (!isLightweight()) {
9544             ComponentPeer peer = getPeer();
9545             if (peer != null) {
9546                 // The Region class has some optimizations. That's why
9547                 // we should manually check whether it's empty and
9548                 // substitute the object ourselves. Otherwise we end up
9549                 // with some incorrect Region object with loX being
9550                 // greater than the hiX for instance.
9551                 if (shape.isEmpty()) {
9552                     shape = Region.EMPTY_REGION;
9553                 }
9554 
9555 
9556                 // Note: the shape is not really copied/cloned. We create
9557                 // the Region object ourselves, so there's no any possibility
9558                 // to modify the object outside of the mixing code.
9559                 // Nullifying compoundShape means that the component has normal shape
9560                 // (or has no shape at all).
9561                 if (shape.equals(getNormalShape())) {
9562                     if (this.compoundShape == null) {
9563                         return;
9564                     }
9565                     this.compoundShape = null;
9566                     peer.applyShape(null);
9567                 } else {
9568                     if (shape.equals(getAppliedShape())) {
9569                         return;
9570                     }
9571                     this.compoundShape = shape;
9572                     Point compAbsolute = getLocationOnWindow();
9573                     if (mixingLog.isLoggable(Level.FINER)) {
9574                         mixingLog.fine("this = " + this +
9575                                 "; compAbsolute=" + compAbsolute + "; shape=" + shape);
9576                     }
9577                     peer.applyShape(shape.getTranslatedRegion(-compAbsolute.x, -compAbsolute.y));
9578                 }
9579             }
9580         }
9581     }
9582 
9583     /**
9584      * Returns the shape previously set with applyCompoundShape().
9585      * If the component is LW or no shape was applied yet,
9586      * the method returns the normal shape.
9587      */
9588     private Region getAppliedShape() {
9589         checkTreeLock();
9590         //XXX: if we allow LW components to have a shape, this must be changed
9591         return (this.compoundShape == null || isLightweight()) ? getNormalShape() : this.compoundShape;
9592     }
9593 
9594     Point getLocationOnWindow() {
9595         checkTreeLock();
9596         Point curLocation = getLocation();
9597 
9598         for (Container parent = getContainer();
9599                 parent != null && !(parent instanceof Window);
9600                 parent = parent.getContainer())
9601         {
9602             curLocation.x += parent.getX();
9603             curLocation.y += parent.getY();
9604         }
9605 
9606         return curLocation;
9607     }
9608 
9609     /**
9610      * Returns the full shape of the component located in window coordinates
9611      */
9612     final Region getNormalShape() {
9613         checkTreeLock();
9614         //XXX: we may take into account a user-specified shape for this component
9615         Point compAbsolute = getLocationOnWindow();
9616         return
9617             Region.getInstanceXYWH(
9618                     compAbsolute.x,
9619                     compAbsolute.y,
9620                     getWidth(),
9621                     getHeight()
9622             );
9623     }
9624 
9625     /**
9626      * Returns the "opaque shape" of the component.
9627      *
9628      * The opaque shape of a lightweight components is the actual shape that
9629      * needs to be cut off of the heavyweight components in order to mix this
9630      * lightweight component correctly with them.
9631      *
9632      * The method is overriden in the java.awt.Container to handle non-opaque
9633      * containers containing opaque children.
9634      *
9635      * See 6637655 for details.
9636      */
9637     Region getOpaqueShape() {
9638         checkTreeLock();
9639         if (mixingCutoutRegion != null) {
9640             return mixingCutoutRegion;
9641         } else {
9642             return getNormalShape();
9643         }
9644     }
9645 
9646     final int getSiblingIndexAbove() {
9647         checkTreeLock();
9648         Container parent = getContainer();
9649         if (parent == null) {
9650             return -1;
9651         }
9652 
9653         int nextAbove = parent.getComponentZOrder(this) - 1;
9654 
9655         return nextAbove < 0 ? -1 : nextAbove;
9656     }
9657 
9658     final ComponentPeer getHWPeerAboveMe() {
9659         checkTreeLock();
9660 
9661         Container cont = getContainer();
9662         int indexAbove = getSiblingIndexAbove();
9663 
9664         while (cont != null) {
9665             for (int i = indexAbove; i > -1; i--) {
9666                 Component comp = cont.getComponent(i);
9667                 if (comp != null && comp.isDisplayable() && !comp.isLightweight()) {
9668                     return comp.getPeer();
9669                 }
9670             }
9671             // traversing the hierarchy up to the closest HW container;
9672             // further traversing may return a component that is not actually
9673             // a native sibling of this component and this kind of z-order
9674             // request may not be allowed by the underlying system (6852051).
9675             if (!cont.isLightweight()) {
9676                 break;
9677             }
9678 
9679             indexAbove = cont.getSiblingIndexAbove();
9680             cont = cont.getContainer();
9681         }
9682 
9683         return null;
9684     }
9685 
9686     final int getSiblingIndexBelow() {
9687         checkTreeLock();
9688         Container parent = getContainer();
9689         if (parent == null) {
9690             return -1;
9691         }
9692 
9693         int nextBelow = parent.getComponentZOrder(this) + 1;
9694 
9695         return nextBelow >= parent.getComponentCount() ? -1 : nextBelow;
9696     }
9697 
9698     final boolean isNonOpaqueForMixing() {
9699         return mixingCutoutRegion != null &&
9700             mixingCutoutRegion.isEmpty();
9701     }
9702 
9703     private Region calculateCurrentShape() {
9704         checkTreeLock();
9705         Region s = getNormalShape();
9706 
9707         if (mixingLog.isLoggable(Level.FINE)) {
9708             mixingLog.fine("this = " + this + "; normalShape=" + s);
9709         }
9710 
9711         if (getContainer() != null) {
9712             Component comp = this;
9713             Container cont = comp.getContainer();
9714 
9715             while (cont != null) {
9716                 for (int index = comp.getSiblingIndexAbove(); index != -1; --index) {
9717                     /* It is assumed that:
9718                      *
9719                      *    getComponent(getContainer().getComponentZOrder(comp)) == comp
9720                      *
9721                      * The assumption has been made according to the current
9722                      * implementation of the Container class.
9723                      */
9724                     Component c = cont.getComponent(index);
9725                     if (c.isLightweight() && c.isShowing()) {
9726                         s = s.getDifference(c.getOpaqueShape());
9727                     }
9728                 }
9729 
9730                 if (cont.isLightweight()) {
9731                     s = s.getIntersection(cont.getNormalShape());
9732                 } else {
9733                     break;
9734                 }
9735 
9736                 comp = cont;
9737                 cont = cont.getContainer();
9738             }
9739         }
9740 
9741         if (mixingLog.isLoggable(Level.FINE)) {
9742             mixingLog.fine("currentShape=" + s);
9743         }
9744 
9745         return s;
9746     }
9747 
9748     void applyCurrentShape() {
9749         checkTreeLock();
9750         if (!areBoundsValid()) {
9751             if (mixingLog.isLoggable(Level.FINE)) {
9752                 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid());
9753             }
9754             return; // Because applyCompoundShape() ignores such components anyway
9755         }
9756         if (mixingLog.isLoggable(Level.FINE)) {
9757             mixingLog.fine("this = " + this);
9758         }
9759         applyCompoundShape(calculateCurrentShape());
9760     }
9761 
9762     final void subtractAndApplyShape(Region s) {
9763         checkTreeLock();
9764 
9765         if (mixingLog.isLoggable(Level.FINE)) {
9766             mixingLog.fine("this = " + this + "; s=" + s);
9767         }
9768 
9769         applyCompoundShape(getAppliedShape().getDifference(s));
9770     }
9771 
9772     private final void applyCurrentShapeBelowMe() {
9773         checkTreeLock();
9774         Container parent = getContainer();
9775         if (parent != null && parent.isShowing()) {
9776             // First, reapply shapes of my siblings
9777             parent.recursiveApplyCurrentShape(getSiblingIndexBelow());
9778 
9779             // Second, if my container is non-opaque, reapply shapes of siblings of my container
9780             Container parent2 = parent.getContainer();
9781             while (!parent.isOpaque() && parent2 != null) {
9782                 parent2.recursiveApplyCurrentShape(parent.getSiblingIndexBelow());
9783 
9784                 parent = parent2;
9785                 parent2 = parent.getContainer();
9786             }
9787         }
9788     }
9789 
9790     final void subtractAndApplyShapeBelowMe() {
9791         checkTreeLock();
9792         Container parent = getContainer();
9793         if (parent != null && isShowing()) {
9794             Region opaqueShape = getOpaqueShape();
9795 
9796             // First, cut my siblings
9797             parent.recursiveSubtractAndApplyShape(opaqueShape, getSiblingIndexBelow());
9798 
9799             // Second, if my container is non-opaque, cut siblings of my container
9800             Container parent2 = parent.getContainer();
9801             while (!parent.isOpaque() && parent2 != null) {
9802                 parent2.recursiveSubtractAndApplyShape(opaqueShape, parent.getSiblingIndexBelow());
9803 
9804                 parent = parent2;
9805                 parent2 = parent.getContainer();
9806             }
9807         }
9808     }
9809 
9810     void mixOnShowing() {
9811         synchronized (getTreeLock()) {
9812             if (mixingLog.isLoggable(Level.FINE)) {
9813                 mixingLog.fine("this = " + this);
9814             }
9815             if (!isMixingNeeded()) {
9816                 return;
9817             }
9818             if (isLightweight()) {
9819                 subtractAndApplyShapeBelowMe();
9820             } else {
9821                 applyCurrentShape();
9822             }
9823         }
9824     }
9825 
9826     void mixOnHiding(boolean isLightweight) {
9827         // We cannot be sure that the peer exists at this point, so we need the argument
9828         //    to find out whether the hiding component is (well, actually was) a LW or a HW.
9829         synchronized (getTreeLock()) {
9830             if (mixingLog.isLoggable(Level.FINE)) {
9831                 mixingLog.fine("this = " + this + "; isLightweight = " + isLightweight);
9832             }
9833             if (!isMixingNeeded()) {
9834                 return;
9835             }
9836             if (isLightweight) {
9837                 applyCurrentShapeBelowMe();
9838             }
9839         }
9840     }
9841 
9842     void mixOnReshaping() {
9843         synchronized (getTreeLock()) {
9844             if (mixingLog.isLoggable(Level.FINE)) {
9845                 mixingLog.fine("this = " + this);
9846             }
9847             if (!isMixingNeeded()) {
9848                 return;
9849             }
9850             if (isLightweight()) {
9851                 applyCurrentShapeBelowMe();
9852             } else {
9853                 applyCurrentShape();
9854             }
9855         }
9856     }
9857 
9858     void mixOnZOrderChanging(int oldZorder, int newZorder) {
9859         synchronized (getTreeLock()) {
9860             boolean becameHigher = newZorder < oldZorder;
9861             Container parent = getContainer();
9862 
9863             if (mixingLog.isLoggable(Level.FINE)) {
9864                 mixingLog.fine("this = " + this +
9865                     "; oldZorder=" + oldZorder + "; newZorder=" + newZorder + "; parent=" + parent);
9866             }
9867             if (!isMixingNeeded()) {
9868                 return;
9869             }
9870             if (isLightweight()) {
9871                 if (becameHigher) {
9872                     if (parent != null && isShowing()) {
9873                         parent.recursiveSubtractAndApplyShape(getOpaqueShape(), getSiblingIndexBelow(), oldZorder);
9874                     }
9875                 } else {
9876                     if (parent != null) {
9877                         parent.recursiveApplyCurrentShape(oldZorder, newZorder);
9878                     }
9879                 }
9880             } else {
9881                 if (becameHigher) {
9882                     applyCurrentShape();
9883                 } else {
9884                     if (parent != null) {
9885                         Region shape = getAppliedShape();
9886 
9887                         for (int index = oldZorder; index < newZorder; index++) {
9888                             Component c = parent.getComponent(index);
9889                             if (c.isLightweight() && c.isShowing()) {
9890                                 shape = shape.getDifference(c.getOpaqueShape());
9891                             }
9892                         }
9893                         applyCompoundShape(shape);
9894                     }
9895                 }
9896             }
9897         }
9898     }
9899 
9900     void mixOnValidating() {
9901         // This method gets overriden in the Container. Obviously, a plain
9902         // non-container components don't need to handle validation.
9903     }
9904 
9905     final boolean isMixingNeeded() {
9906         if (SunToolkit.getSunAwtDisableMixing()) {
9907             if (mixingLog.isLoggable(Level.FINEST)) {
9908                 mixingLog.finest("this = " + this + "; Mixing disabled via sun.awt.disableMixing");
9909             }
9910             return false;
9911         }
9912         if (!areBoundsValid()) {
9913             if (mixingLog.isLoggable(Level.FINE)) {
9914                 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid());
9915             }
9916             return false;
9917         }
9918         Window window = getContainingWindow();
9919         if (window != null) {
9920             if (!window.hasHeavyweightDescendants() || !window.hasLightweightDescendants()) {
9921                 if (mixingLog.isLoggable(Level.FINE)) {
9922                     mixingLog.fine("containing window = " + window +
9923                             "; has h/w descendants = " + window.hasHeavyweightDescendants() +
9924                             "; has l/w descendants = " + window.hasLightweightDescendants());
9925                 }
9926                 return false;
9927             }
9928         } else {
9929             if (mixingLog.isLoggable(Level.FINE)) {
9930                 mixingLog.finest("this = " + this + "; containing window is null");
9931             }
9932             return false;
9933         }
9934         return true;
9935     }
9936 
9937     // ****************** END OF MIXING CODE ********************************
9938 
9939     // Note that the method is overriden in the Window class,
9940     // a window doesn't need to be updated in the Z-order.
9941     void updateZOrder() {
9942         peer.setZOrder(getHWPeerAboveMe());
9943     }
9944 
9945 }