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