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 setMixingCutoutShape(Component comp, Shape shape) {
 847                 comp.setMixingCutoutShape(shape);
 848             }
 849 
 850             public void setGraphicsConfiguration(Component comp,
 851                     GraphicsConfiguration gc)
 852             {
 853                 comp.setGraphicsConfiguration(gc);
 854             }
 855             public void requestFocus(Component comp, FocusEvent.Cause cause) {
 856                 comp.requestFocus(cause);
 857             }
 858             public boolean canBeFocusOwner(Component comp) {
 859                 return comp.canBeFocusOwner();
 860             }
 861 
 862             public boolean isVisible(Component comp) {
 863                 return comp.isVisible_NoClientCode();
 864             }
 865             public void setRequestFocusController
 866                 (RequestFocusController requestController)
 867             {
 868                  Component.setRequestFocusController(requestController);
 869             }
 870             public AppContext getAppContext(Component comp) {
 871                  return comp.appContext;
 872             }
 873             public void setAppContext(Component comp, AppContext appContext) {
 874                  comp.appContext = appContext;
 875             }
 876             public Container getParent(Component comp) {
 877                 return comp.getParent_NoClientCode();
 878             }
 879             public void setParent(Component comp, Container parent) {
 880                 comp.parent = parent;
 881             }
 882             public void setSize(Component comp, int width, int height) {
 883                 comp.width = width;
 884                 comp.height = height;
 885             }
 886             public Point getLocation(Component comp) {
 887                 return comp.location_NoClientCode();
 888             }
 889             public void setLocation(Component comp, int x, int y) {
 890                 comp.x = x;
 891                 comp.y = y;
 892             }
 893             public boolean isEnabled(Component comp) {
 894                 return comp.isEnabledImpl();
 895             }
 896             public boolean isDisplayable(Component comp) {
 897                 return comp.peer != null;
 898             }
 899             public Cursor getCursor(Component comp) {
 900                 return comp.getCursor_NoClientCode();
 901             }
 902             @SuppressWarnings("unchecked")
 903             public <T extends ComponentPeer> T getPeer(Component comp) {
 904                 return (T) comp.peer;
 905             }
 906             public void setPeer(Component comp, ComponentPeer peer) {
 907                 comp.peer = peer;
 908             }
 909             public boolean isLightweight(Component comp) {
 910                 return (comp.peer instanceof LightweightPeer);
 911             }
 912             public boolean getIgnoreRepaint(Component comp) {
 913                 return comp.ignoreRepaint;
 914             }
 915             public int getWidth(Component comp) {
 916                 return comp.width;
 917             }
 918             public int getHeight(Component comp) {
 919                 return comp.height;
 920             }
 921             public int getX(Component comp) {
 922                 return comp.x;
 923             }
 924             public int getY(Component comp) {
 925                 return comp.y;
 926             }
 927             public Color getForeground(Component comp) {
 928                 return comp.foreground;
 929             }
 930             public Color getBackground(Component comp) {
 931                 return comp.background;
 932             }
 933             public void setBackground(Component comp, Color background) {
 934                 comp.background = background;
 935             }
 936             public Font getFont(Component comp) {
 937                 return comp.getFont_NoClientCode();
 938             }
 939             public void processEvent(Component comp, AWTEvent e) {
 940                 comp.processEvent(e);
 941             }
 942 
 943             public AccessControlContext getAccessControlContext(Component comp) {
 944                 return comp.getAccessControlContext();
 945             }
 946 
 947             public void revalidateSynchronously(Component comp) {
 948                 comp.revalidateSynchronously();
 949             }
 950 
 951             @Override
 952             public void createBufferStrategy(Component comp, int numBuffers,
 953                     BufferCapabilities caps) throws AWTException {
 954                 comp.createBufferStrategy(numBuffers, caps);
 955             }
 956 
 957             @Override
 958             public BufferStrategy getBufferStrategy(Component comp) {
 959                 return comp.getBufferStrategy();
 960             }
 961         });
 962     }
 963 
 964     /**
 965      * Constructs a new component. Class {@code Component} can be
 966      * extended directly to create a lightweight component that does not
 967      * utilize an opaque native window. A lightweight component must be
 968      * hosted by a native container somewhere higher up in the component
 969      * tree (for example, by a {@code Frame} object).
 970      */
 971     protected Component() {
 972         appContext = AppContext.getAppContext();
 973     }
 974 
 975     @SuppressWarnings({"rawtypes", "unchecked"})
 976     void initializeFocusTraversalKeys() {
 977         focusTraversalKeys = new Set[3];
 978     }
 979 
 980     /**
 981      * Constructs a name for this component.  Called by {@code getName}
 982      * when the name is {@code null}.
 983      */
 984     String constructComponentName() {
 985         return null; // For strict compliance with prior platform versions, a Component
 986                      // that doesn't set its name should return null from
 987                      // getName()
 988     }
 989 
 990     /**
 991      * Gets the name of the component.
 992      * @return this component's name
 993      * @see    #setName
 994      * @since 1.1
 995      */
 996     public String getName() {
 997         if (name == null && !nameExplicitlySet) {
 998             synchronized(getObjectLock()) {
 999                 if (name == null && !nameExplicitlySet)
1000                     name = constructComponentName();
1001             }
1002         }
1003         return name;
1004     }
1005 
1006     /**
1007      * Sets the name of the component to the specified string.
1008      * @param name  the string that is to be this
1009      *           component's name
1010      * @see #getName
1011      * @since 1.1
1012      */
1013     public void setName(String name) {
1014         String oldName;
1015         synchronized(getObjectLock()) {
1016             oldName = this.name;
1017             this.name = name;
1018             nameExplicitlySet = true;
1019         }
1020         firePropertyChange("name", oldName, name);
1021     }
1022 
1023     /**
1024      * Gets the parent of this component.
1025      * @return the parent container of this component
1026      * @since 1.0
1027      */
1028     public Container getParent() {
1029         return getParent_NoClientCode();
1030     }
1031 
1032     // NOTE: This method may be called by privileged threads.
1033     //       This functionality is implemented in a package-private method
1034     //       to insure that it cannot be overridden by client subclasses.
1035     //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
1036     final Container getParent_NoClientCode() {
1037         return parent;
1038     }
1039 
1040     // This method is overridden in the Window class to return null,
1041     //    because the parent field of the Window object contains
1042     //    the owner of the window, not its parent.
1043     Container getContainer() {
1044         return getParent_NoClientCode();
1045     }
1046 
1047     /**
1048      * Associate a {@code DropTarget} with this component.
1049      * The {@code Component} will receive drops only if it
1050      * is enabled.
1051      *
1052      * @see #isEnabled
1053      * @param dt The DropTarget
1054      */
1055 
1056     public synchronized void setDropTarget(DropTarget dt) {
1057         if (dt == dropTarget || (dropTarget != null && dropTarget.equals(dt)))
1058             return;
1059 
1060         DropTarget old;
1061 
1062         if ((old = dropTarget) != null) {
1063             dropTarget.removeNotify();
1064 
1065             DropTarget t = dropTarget;
1066 
1067             dropTarget = null;
1068 
1069             try {
1070                 t.setComponent(null);
1071             } catch (IllegalArgumentException iae) {
1072                 // ignore it.
1073             }
1074         }
1075 
1076         // if we have a new one, and we have a peer, add it!
1077 
1078         if ((dropTarget = dt) != null) {
1079             try {
1080                 dropTarget.setComponent(this);
1081                 dropTarget.addNotify();
1082             } catch (IllegalArgumentException iae) {
1083                 if (old != null) {
1084                     try {
1085                         old.setComponent(this);
1086                         dropTarget.addNotify();
1087                     } catch (IllegalArgumentException iae1) {
1088                         // ignore it!
1089                     }
1090                 }
1091             }
1092         }
1093     }
1094 
1095     /**
1096      * Gets the {@code DropTarget} associated with this
1097      * {@code Component}.
1098      *
1099      * @return the drop target
1100      */
1101 
1102     public synchronized DropTarget getDropTarget() { return dropTarget; }
1103 
1104     /**
1105      * Gets the {@code GraphicsConfiguration} associated with this
1106      * {@code Component}.
1107      * If the {@code Component} has not been assigned a specific
1108      * {@code GraphicsConfiguration},
1109      * the {@code GraphicsConfiguration} of the
1110      * {@code Component} object's top-level container is
1111      * returned.
1112      * If the {@code Component} has been created, but not yet added
1113      * to a {@code Container}, this method returns {@code null}.
1114      *
1115      * @return the {@code GraphicsConfiguration} used by this
1116      *          {@code Component} or {@code null}
1117      * @since 1.3
1118      */
1119     public GraphicsConfiguration getGraphicsConfiguration() {
1120         return getGraphicsConfiguration_NoClientCode();
1121     }
1122 
1123     final GraphicsConfiguration getGraphicsConfiguration_NoClientCode() {
1124         return graphicsConfig;
1125     }
1126 
1127     void setGraphicsConfiguration(GraphicsConfiguration gc) {
1128         synchronized(getTreeLock()) {
1129             if (updateGraphicsData(gc)) {
1130                 removeNotify();
1131                 addNotify();
1132             }
1133         }
1134     }
1135 
1136     boolean updateGraphicsData(GraphicsConfiguration gc) {
1137         checkTreeLock();
1138 
1139         if (graphicsConfig == gc) {
1140             return false;
1141         }
1142         // If component is moved from one screen(hidpi) to another sceeen(lowdpi)
1143         // graphicsConfig property is fired to enable the component to recalculate
1144         // any rendering data, if needed
1145         if (graphicsConfig != null && gc != null) {
1146             firePropertyChange("graphicsConfig", graphicsConfig, gc);
1147         }
1148         graphicsConfig = gc;
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 
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.getParent()) {
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     } // dispatchEventImpl()
5031 
5032     /*
5033      * If newEventsOnly is false, method is called so that ScrollPane can
5034      * override it and handle common-case mouse wheel scrolling.  NOP
5035      * for Component.
5036      */
5037     void autoProcessMouseWheel(MouseWheelEvent e) {}
5038 
5039     /*
5040      * Dispatch given MouseWheelEvent to the first ancestor for which
5041      * MouseWheelEvents are enabled.
5042      *
5043      * Returns whether or not event was dispatched to an ancestor
5044      */
5045     @SuppressWarnings("deprecation")
5046     boolean dispatchMouseWheelToAncestor(MouseWheelEvent e) {
5047         int newX, newY;
5048         newX = e.getX() + getX(); // Coordinates take into account at least
5049         newY = e.getY() + getY(); // the cursor's position relative to this
5050                                   // Component (e.getX()), and this Component's
5051                                   // position relative to its parent.
5052         MouseWheelEvent newMWE;
5053 
5054         if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
5055             eventLog.finest("dispatchMouseWheelToAncestor");
5056             eventLog.finest("orig event src is of " + e.getSource().getClass());
5057         }
5058 
5059         /* parent field for Window refers to the owning Window.
5060          * MouseWheelEvents should NOT be propagated into owning Windows
5061          */
5062         synchronized (getTreeLock()) {
5063             Container anc = getParent();
5064             while (anc != null && !anc.eventEnabled(e)) {
5065                 // fix coordinates to be relative to new event source
5066                 newX += anc.getX();
5067                 newY += anc.getY();
5068 
5069                 if (!(anc instanceof Window)) {
5070                     anc = anc.getParent();
5071                 }
5072                 else {
5073                     break;
5074                 }
5075             }
5076 
5077             if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
5078                 eventLog.finest("new event src is " + anc.getClass());
5079             }
5080 
5081             if (anc != null && anc.eventEnabled(e)) {
5082                 // Change event to be from new source, with new x,y
5083                 // For now, just create a new event - yucky
5084 
5085                 newMWE = new MouseWheelEvent(anc, // new source
5086                                              e.getID(),
5087                                              e.getWhen(),
5088                                              e.getModifiers(),
5089                                              newX, // x relative to new source
5090                                              newY, // y relative to new source
5091                                              e.getXOnScreen(),
5092                                              e.getYOnScreen(),
5093                                              e.getClickCount(),
5094                                              e.isPopupTrigger(),
5095                                              e.getScrollType(),
5096                                              e.getScrollAmount(),
5097                                              e.getWheelRotation(),
5098                                              e.getPreciseWheelRotation());
5099                 ((AWTEvent)e).copyPrivateDataInto(newMWE);
5100                 // When dispatching a wheel event to
5101                 // ancestor, there is no need trying to find descendant
5102                 // lightweights to dispatch event to.
5103                 // If we dispatch the event to toplevel ancestor,
5104                 // this could enclose the loop: 6480024.
5105                 anc.dispatchEventToSelf(newMWE);
5106                 if (newMWE.isConsumed()) {
5107                     e.consume();
5108                 }
5109                 return true;
5110             }
5111         }
5112         return false;
5113     }
5114 
5115     boolean areInputMethodsEnabled() {
5116         // in 1.2, we assume input method support is required for all
5117         // components that handle key events, but components can turn off
5118         // input methods by calling enableInputMethods(false).
5119         return ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) &&
5120             ((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 || keyListener != null);
5121     }
5122 
5123     // REMIND: remove when filtering is handled at lower level
5124     boolean eventEnabled(AWTEvent e) {
5125         return eventTypeEnabled(e.id);
5126     }
5127 
5128     boolean eventTypeEnabled(int type) {
5129         switch(type) {
5130           case ComponentEvent.COMPONENT_MOVED:
5131           case ComponentEvent.COMPONENT_RESIZED:
5132           case ComponentEvent.COMPONENT_SHOWN:
5133           case ComponentEvent.COMPONENT_HIDDEN:
5134               if ((eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||
5135                   componentListener != null) {
5136                   return true;
5137               }
5138               break;
5139           case FocusEvent.FOCUS_GAINED:
5140           case FocusEvent.FOCUS_LOST:
5141               if ((eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0 ||
5142                   focusListener != null) {
5143                   return true;
5144               }
5145               break;
5146           case KeyEvent.KEY_PRESSED:
5147           case KeyEvent.KEY_RELEASED:
5148           case KeyEvent.KEY_TYPED:
5149               if ((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 ||
5150                   keyListener != null) {
5151                   return true;
5152               }
5153               break;
5154           case MouseEvent.MOUSE_PRESSED:
5155           case MouseEvent.MOUSE_RELEASED:
5156           case MouseEvent.MOUSE_ENTERED:
5157           case MouseEvent.MOUSE_EXITED:
5158           case MouseEvent.MOUSE_CLICKED:
5159               if ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0 ||
5160                   mouseListener != null) {
5161                   return true;
5162               }
5163               break;
5164           case MouseEvent.MOUSE_MOVED:
5165           case MouseEvent.MOUSE_DRAGGED:
5166               if ((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0 ||
5167                   mouseMotionListener != null) {
5168                   return true;
5169               }
5170               break;
5171           case MouseEvent.MOUSE_WHEEL:
5172               if ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0 ||
5173                   mouseWheelListener != null) {
5174                   return true;
5175               }
5176               break;
5177           case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED:
5178           case InputMethodEvent.CARET_POSITION_CHANGED:
5179               if ((eventMask & AWTEvent.INPUT_METHOD_EVENT_MASK) != 0 ||
5180                   inputMethodListener != null) {
5181                   return true;
5182               }
5183               break;
5184           case HierarchyEvent.HIERARCHY_CHANGED:
5185               if ((eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
5186                   hierarchyListener != null) {
5187                   return true;
5188               }
5189               break;
5190           case HierarchyEvent.ANCESTOR_MOVED:
5191           case HierarchyEvent.ANCESTOR_RESIZED:
5192               if ((eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 ||
5193                   hierarchyBoundsListener != null) {
5194                   return true;
5195               }
5196               break;
5197           case ActionEvent.ACTION_PERFORMED:
5198               if ((eventMask & AWTEvent.ACTION_EVENT_MASK) != 0) {
5199                   return true;
5200               }
5201               break;
5202           case TextEvent.TEXT_VALUE_CHANGED:
5203               if ((eventMask & AWTEvent.TEXT_EVENT_MASK) != 0) {
5204                   return true;
5205               }
5206               break;
5207           case ItemEvent.ITEM_STATE_CHANGED:
5208               if ((eventMask & AWTEvent.ITEM_EVENT_MASK) != 0) {
5209                   return true;
5210               }
5211               break;
5212           case AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED:
5213               if ((eventMask & AWTEvent.ADJUSTMENT_EVENT_MASK) != 0) {
5214                   return true;
5215               }
5216               break;
5217           default:
5218               break;
5219         }
5220         //
5221         // Always pass on events defined by external programs.
5222         //
5223         if (type > AWTEvent.RESERVED_ID_MAX) {
5224             return true;
5225         }
5226         return false;
5227     }
5228 
5229     /**
5230      * @deprecated As of JDK version 1.1,
5231      * replaced by dispatchEvent(AWTEvent).
5232      */
5233     @Deprecated
5234     public boolean postEvent(Event e) {
5235         ComponentPeer peer = this.peer;
5236 
5237         if (handleEvent(e)) {
5238             e.consume();
5239             return true;
5240         }
5241 
5242         Component parent = this.parent;
5243         int eventx = e.x;
5244         int eventy = e.y;
5245         if (parent != null) {
5246             e.translate(x, y);
5247             if (parent.postEvent(e)) {
5248                 e.consume();
5249                 return true;
5250             }
5251             // restore coords
5252             e.x = eventx;
5253             e.y = eventy;
5254         }
5255         return false;
5256     }
5257 
5258     // Event source interfaces
5259 
5260     /**
5261      * Adds the specified component listener to receive component events from
5262      * this component.
5263      * If listener {@code l} is {@code null},
5264      * no exception is thrown and no action is performed.
5265      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5266      * >AWT Threading Issues</a> for details on AWT's threading model.
5267      *
5268      * @param    l   the component listener
5269      * @see      java.awt.event.ComponentEvent
5270      * @see      java.awt.event.ComponentListener
5271      * @see      #removeComponentListener
5272      * @see      #getComponentListeners
5273      * @since    1.1
5274      */
5275     public synchronized void addComponentListener(ComponentListener l) {
5276         if (l == null) {
5277             return;
5278         }
5279         componentListener = AWTEventMulticaster.add(componentListener, l);
5280         newEventsOnly = true;
5281     }
5282 
5283     /**
5284      * Removes the specified component listener so that it no longer
5285      * receives component events from this component. This method performs
5286      * no function, nor does it throw an exception, if the listener
5287      * specified by the argument was not previously added to this component.
5288      * If listener {@code l} is {@code null},
5289      * no exception is thrown and no action is performed.
5290      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5291      * >AWT Threading Issues</a> for details on AWT's threading model.
5292      * @param    l   the component listener
5293      * @see      java.awt.event.ComponentEvent
5294      * @see      java.awt.event.ComponentListener
5295      * @see      #addComponentListener
5296      * @see      #getComponentListeners
5297      * @since    1.1
5298      */
5299     public synchronized void removeComponentListener(ComponentListener l) {
5300         if (l == null) {
5301             return;
5302         }
5303         componentListener = AWTEventMulticaster.remove(componentListener, l);
5304     }
5305 
5306     /**
5307      * Returns an array of all the component listeners
5308      * registered on this component.
5309      *
5310      * @return all {@code ComponentListener}s of this component
5311      *         or an empty array if no component
5312      *         listeners are currently registered
5313      *
5314      * @see #addComponentListener
5315      * @see #removeComponentListener
5316      * @since 1.4
5317      */
5318     public synchronized ComponentListener[] getComponentListeners() {
5319         return getListeners(ComponentListener.class);
5320     }
5321 
5322     /**
5323      * Adds the specified focus listener to receive focus events from
5324      * this component when this component gains input focus.
5325      * If listener {@code l} is {@code null},
5326      * no exception is thrown and no action is performed.
5327      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5328      * >AWT Threading Issues</a> for details on AWT's threading model.
5329      *
5330      * @param    l   the focus listener
5331      * @see      java.awt.event.FocusEvent
5332      * @see      java.awt.event.FocusListener
5333      * @see      #removeFocusListener
5334      * @see      #getFocusListeners
5335      * @since    1.1
5336      */
5337     public synchronized void addFocusListener(FocusListener l) {
5338         if (l == null) {
5339             return;
5340         }
5341         focusListener = AWTEventMulticaster.add(focusListener, l);
5342         newEventsOnly = true;
5343 
5344         // if this is a lightweight component, enable focus events
5345         // in the native container.
5346         if (peer instanceof LightweightPeer) {
5347             parent.proxyEnableEvents(AWTEvent.FOCUS_EVENT_MASK);
5348         }
5349     }
5350 
5351     /**
5352      * Removes the specified focus listener so that it no longer
5353      * receives focus events from this component. This method performs
5354      * no function, nor does it throw an exception, if the listener
5355      * specified by the argument was not previously added to this component.
5356      * If listener {@code l} is {@code null},
5357      * no exception is thrown and no action is performed.
5358      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5359      * >AWT Threading Issues</a> for details on AWT's threading model.
5360      *
5361      * @param    l   the focus listener
5362      * @see      java.awt.event.FocusEvent
5363      * @see      java.awt.event.FocusListener
5364      * @see      #addFocusListener
5365      * @see      #getFocusListeners
5366      * @since    1.1
5367      */
5368     public synchronized void removeFocusListener(FocusListener l) {
5369         if (l == null) {
5370             return;
5371         }
5372         focusListener = AWTEventMulticaster.remove(focusListener, l);
5373     }
5374 
5375     /**
5376      * Returns an array of all the focus listeners
5377      * registered on this component.
5378      *
5379      * @return all of this component's {@code FocusListener}s
5380      *         or an empty array if no component
5381      *         listeners are currently registered
5382      *
5383      * @see #addFocusListener
5384      * @see #removeFocusListener
5385      * @since 1.4
5386      */
5387     public synchronized FocusListener[] getFocusListeners() {
5388         return getListeners(FocusListener.class);
5389     }
5390 
5391     /**
5392      * Adds the specified hierarchy listener to receive hierarchy changed
5393      * events from this component when the hierarchy to which this container
5394      * belongs changes.
5395      * If listener {@code l} is {@code null},
5396      * no exception is thrown and no action is performed.
5397      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5398      * >AWT Threading Issues</a> for details on AWT's threading model.
5399      *
5400      * @param    l   the hierarchy listener
5401      * @see      java.awt.event.HierarchyEvent
5402      * @see      java.awt.event.HierarchyListener
5403      * @see      #removeHierarchyListener
5404      * @see      #getHierarchyListeners
5405      * @since    1.3
5406      */
5407     public void addHierarchyListener(HierarchyListener l) {
5408         if (l == null) {
5409             return;
5410         }
5411         boolean notifyAncestors;
5412         synchronized (this) {
5413             notifyAncestors =
5414                 (hierarchyListener == null &&
5415                  (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0);
5416             hierarchyListener = AWTEventMulticaster.add(hierarchyListener, l);
5417             notifyAncestors = (notifyAncestors && hierarchyListener != null);
5418             newEventsOnly = true;
5419         }
5420         if (notifyAncestors) {
5421             synchronized (getTreeLock()) {
5422                 adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK,
5423                                                 1);
5424             }
5425         }
5426     }
5427 
5428     /**
5429      * Removes the specified hierarchy listener so that it no longer
5430      * receives hierarchy changed events from this component. This method
5431      * performs no function, nor does it throw an exception, if the listener
5432      * specified by the argument was not previously added to this component.
5433      * If listener {@code l} is {@code null},
5434      * no exception is thrown and no action is performed.
5435      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5436      * >AWT Threading Issues</a> for details on AWT's threading model.
5437      *
5438      * @param    l   the hierarchy listener
5439      * @see      java.awt.event.HierarchyEvent
5440      * @see      java.awt.event.HierarchyListener
5441      * @see      #addHierarchyListener
5442      * @see      #getHierarchyListeners
5443      * @since    1.3
5444      */
5445     public void removeHierarchyListener(HierarchyListener l) {
5446         if (l == null) {
5447             return;
5448         }
5449         boolean notifyAncestors;
5450         synchronized (this) {
5451             notifyAncestors =
5452                 (hierarchyListener != null &&
5453                  (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0);
5454             hierarchyListener =
5455                 AWTEventMulticaster.remove(hierarchyListener, l);
5456             notifyAncestors = (notifyAncestors && hierarchyListener == null);
5457         }
5458         if (notifyAncestors) {
5459             synchronized (getTreeLock()) {
5460                 adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK,
5461                                                 -1);
5462             }
5463         }
5464     }
5465 
5466     /**
5467      * Returns an array of all the hierarchy listeners
5468      * registered on this component.
5469      *
5470      * @return all of this component's {@code HierarchyListener}s
5471      *         or an empty array if no hierarchy
5472      *         listeners are currently registered
5473      *
5474      * @see      #addHierarchyListener
5475      * @see      #removeHierarchyListener
5476      * @since    1.4
5477      */
5478     public synchronized HierarchyListener[] getHierarchyListeners() {
5479         return getListeners(HierarchyListener.class);
5480     }
5481 
5482     /**
5483      * Adds the specified hierarchy bounds listener to receive hierarchy
5484      * bounds events from this component when the hierarchy to which this
5485      * container belongs changes.
5486      * If listener {@code l} is {@code null},
5487      * no exception is thrown and no action is performed.
5488      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5489      * >AWT Threading Issues</a> for details on AWT's threading model.
5490      *
5491      * @param    l   the hierarchy bounds listener
5492      * @see      java.awt.event.HierarchyEvent
5493      * @see      java.awt.event.HierarchyBoundsListener
5494      * @see      #removeHierarchyBoundsListener
5495      * @see      #getHierarchyBoundsListeners
5496      * @since    1.3
5497      */
5498     public void addHierarchyBoundsListener(HierarchyBoundsListener l) {
5499         if (l == null) {
5500             return;
5501         }
5502         boolean notifyAncestors;
5503         synchronized (this) {
5504             notifyAncestors =
5505                 (hierarchyBoundsListener == null &&
5506                  (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0);
5507             hierarchyBoundsListener =
5508                 AWTEventMulticaster.add(hierarchyBoundsListener, l);
5509             notifyAncestors = (notifyAncestors &&
5510                                hierarchyBoundsListener != null);
5511             newEventsOnly = true;
5512         }
5513         if (notifyAncestors) {
5514             synchronized (getTreeLock()) {
5515                 adjustListeningChildrenOnParent(
5516                                                 AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, 1);
5517             }
5518         }
5519     }
5520 
5521     /**
5522      * Removes the specified hierarchy bounds listener so that it no longer
5523      * receives hierarchy bounds events from this component. This method
5524      * performs no function, nor does it throw an exception, if the listener
5525      * specified by the argument was not previously added to this component.
5526      * If listener {@code l} is {@code null},
5527      * no exception is thrown and no action is performed.
5528      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5529      * >AWT Threading Issues</a> for details on AWT's threading model.
5530      *
5531      * @param    l   the hierarchy bounds listener
5532      * @see      java.awt.event.HierarchyEvent
5533      * @see      java.awt.event.HierarchyBoundsListener
5534      * @see      #addHierarchyBoundsListener
5535      * @see      #getHierarchyBoundsListeners
5536      * @since    1.3
5537      */
5538     public void removeHierarchyBoundsListener(HierarchyBoundsListener l) {
5539         if (l == null) {
5540             return;
5541         }
5542         boolean notifyAncestors;
5543         synchronized (this) {
5544             notifyAncestors =
5545                 (hierarchyBoundsListener != null &&
5546                  (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0);
5547             hierarchyBoundsListener =
5548                 AWTEventMulticaster.remove(hierarchyBoundsListener, l);
5549             notifyAncestors = (notifyAncestors &&
5550                                hierarchyBoundsListener == null);
5551         }
5552         if (notifyAncestors) {
5553             synchronized (getTreeLock()) {
5554                 adjustListeningChildrenOnParent(
5555                                                 AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, -1);
5556             }
5557         }
5558     }
5559 
5560     // Should only be called while holding the tree lock
5561     int numListening(long mask) {
5562         // One mask or the other, but not neither or both.
5563         if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
5564             if ((mask != AWTEvent.HIERARCHY_EVENT_MASK) &&
5565                 (mask != AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK))
5566             {
5567                 eventLog.fine("Assertion failed");
5568             }
5569         }
5570         if ((mask == AWTEvent.HIERARCHY_EVENT_MASK &&
5571              (hierarchyListener != null ||
5572               (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0)) ||
5573             (mask == AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK &&
5574              (hierarchyBoundsListener != null ||
5575               (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0))) {
5576             return 1;
5577         } else {
5578             return 0;
5579         }
5580     }
5581 
5582     // Should only be called while holding tree lock
5583     int countHierarchyMembers() {
5584         return 1;
5585     }
5586     // Should only be called while holding the tree lock
5587     int createHierarchyEvents(int id, Component changed,
5588                               Container changedParent, long changeFlags,
5589                               boolean enabledOnToolkit) {
5590         switch (id) {
5591           case HierarchyEvent.HIERARCHY_CHANGED:
5592               if (hierarchyListener != null ||
5593                   (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
5594                   enabledOnToolkit) {
5595                   HierarchyEvent e = new HierarchyEvent(this, id, changed,
5596                                                         changedParent,
5597                                                         changeFlags);
5598                   dispatchEvent(e);
5599                   return 1;
5600               }
5601               break;
5602           case HierarchyEvent.ANCESTOR_MOVED:
5603           case HierarchyEvent.ANCESTOR_RESIZED:
5604               if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
5605                   if (changeFlags != 0) {
5606                       eventLog.fine("Assertion (changeFlags == 0) failed");
5607                   }
5608               }
5609               if (hierarchyBoundsListener != null ||
5610                   (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 ||
5611                   enabledOnToolkit) {
5612                   HierarchyEvent e = new HierarchyEvent(this, id, changed,
5613                                                         changedParent);
5614                   dispatchEvent(e);
5615                   return 1;
5616               }
5617               break;
5618           default:
5619               // assert false
5620               if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
5621                   eventLog.fine("This code must never be reached");
5622               }
5623               break;
5624         }
5625         return 0;
5626     }
5627 
5628     /**
5629      * Returns an array of all the hierarchy bounds listeners
5630      * registered on this component.
5631      *
5632      * @return all of this component's {@code HierarchyBoundsListener}s
5633      *         or an empty array if no hierarchy bounds
5634      *         listeners are currently registered
5635      *
5636      * @see      #addHierarchyBoundsListener
5637      * @see      #removeHierarchyBoundsListener
5638      * @since    1.4
5639      */
5640     public synchronized HierarchyBoundsListener[] getHierarchyBoundsListeners() {
5641         return getListeners(HierarchyBoundsListener.class);
5642     }
5643 
5644     /*
5645      * Should only be called while holding the tree lock.
5646      * It's added only for overriding in java.awt.Window
5647      * because parent in Window is owner.
5648      */
5649     void adjustListeningChildrenOnParent(long mask, int num) {
5650         if (parent != null) {
5651             parent.adjustListeningChildren(mask, num);
5652         }
5653     }
5654 
5655     /**
5656      * Adds the specified key listener to receive key events from
5657      * this component.
5658      * If l is null, no exception is thrown and no action is performed.
5659      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5660      * >AWT Threading Issues</a> for details on AWT's threading model.
5661      *
5662      * @param    l   the key listener.
5663      * @see      java.awt.event.KeyEvent
5664      * @see      java.awt.event.KeyListener
5665      * @see      #removeKeyListener
5666      * @see      #getKeyListeners
5667      * @since    1.1
5668      */
5669     public synchronized void addKeyListener(KeyListener l) {
5670         if (l == null) {
5671             return;
5672         }
5673         keyListener = AWTEventMulticaster.add(keyListener, l);
5674         newEventsOnly = true;
5675 
5676         // if this is a lightweight component, enable key events
5677         // in the native container.
5678         if (peer instanceof LightweightPeer) {
5679             parent.proxyEnableEvents(AWTEvent.KEY_EVENT_MASK);
5680         }
5681     }
5682 
5683     /**
5684      * Removes the specified key listener so that it no longer
5685      * receives key events from this component. This method performs
5686      * no function, nor does it throw an exception, if the listener
5687      * specified by the argument was not previously added to this component.
5688      * If listener {@code l} is {@code null},
5689      * no exception is thrown and no action is performed.
5690      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5691      * >AWT Threading Issues</a> for details on AWT's threading model.
5692      *
5693      * @param    l   the key listener
5694      * @see      java.awt.event.KeyEvent
5695      * @see      java.awt.event.KeyListener
5696      * @see      #addKeyListener
5697      * @see      #getKeyListeners
5698      * @since    1.1
5699      */
5700     public synchronized void removeKeyListener(KeyListener l) {
5701         if (l == null) {
5702             return;
5703         }
5704         keyListener = AWTEventMulticaster.remove(keyListener, l);
5705     }
5706 
5707     /**
5708      * Returns an array of all the key listeners
5709      * registered on this component.
5710      *
5711      * @return all of this component's {@code KeyListener}s
5712      *         or an empty array if no key
5713      *         listeners are currently registered
5714      *
5715      * @see      #addKeyListener
5716      * @see      #removeKeyListener
5717      * @since    1.4
5718      */
5719     public synchronized KeyListener[] getKeyListeners() {
5720         return getListeners(KeyListener.class);
5721     }
5722 
5723     /**
5724      * Adds the specified mouse listener to receive mouse events from
5725      * this component.
5726      * If listener {@code l} is {@code null},
5727      * no exception is thrown and no action is performed.
5728      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5729      * >AWT Threading Issues</a> for details on AWT's threading model.
5730      *
5731      * @param    l   the mouse listener
5732      * @see      java.awt.event.MouseEvent
5733      * @see      java.awt.event.MouseListener
5734      * @see      #removeMouseListener
5735      * @see      #getMouseListeners
5736      * @since    1.1
5737      */
5738     public synchronized void addMouseListener(MouseListener l) {
5739         if (l == null) {
5740             return;
5741         }
5742         mouseListener = AWTEventMulticaster.add(mouseListener,l);
5743         newEventsOnly = true;
5744 
5745         // if this is a lightweight component, enable mouse events
5746         // in the native container.
5747         if (peer instanceof LightweightPeer) {
5748             parent.proxyEnableEvents(AWTEvent.MOUSE_EVENT_MASK);
5749         }
5750     }
5751 
5752     /**
5753      * Removes the specified mouse listener so that it no longer
5754      * receives mouse events from this component. This method performs
5755      * no function, nor does it throw an exception, if the listener
5756      * specified by the argument was not previously added to this component.
5757      * If listener {@code l} is {@code null},
5758      * no exception is thrown and no action is performed.
5759      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5760      * >AWT Threading Issues</a> for details on AWT's threading model.
5761      *
5762      * @param    l   the mouse listener
5763      * @see      java.awt.event.MouseEvent
5764      * @see      java.awt.event.MouseListener
5765      * @see      #addMouseListener
5766      * @see      #getMouseListeners
5767      * @since    1.1
5768      */
5769     public synchronized void removeMouseListener(MouseListener l) {
5770         if (l == null) {
5771             return;
5772         }
5773         mouseListener = AWTEventMulticaster.remove(mouseListener, l);
5774     }
5775 
5776     /**
5777      * Returns an array of all the mouse listeners
5778      * registered on this component.
5779      *
5780      * @return all of this component's {@code MouseListener}s
5781      *         or an empty array if no mouse
5782      *         listeners are currently registered
5783      *
5784      * @see      #addMouseListener
5785      * @see      #removeMouseListener
5786      * @since    1.4
5787      */
5788     public synchronized MouseListener[] getMouseListeners() {
5789         return getListeners(MouseListener.class);
5790     }
5791 
5792     /**
5793      * Adds the specified mouse motion listener to receive mouse motion
5794      * events from this component.
5795      * If listener {@code l} is {@code null},
5796      * no exception is thrown and no action is performed.
5797      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5798      * >AWT Threading Issues</a> for details on AWT's threading model.
5799      *
5800      * @param    l   the mouse motion listener
5801      * @see      java.awt.event.MouseEvent
5802      * @see      java.awt.event.MouseMotionListener
5803      * @see      #removeMouseMotionListener
5804      * @see      #getMouseMotionListeners
5805      * @since    1.1
5806      */
5807     public synchronized void addMouseMotionListener(MouseMotionListener l) {
5808         if (l == null) {
5809             return;
5810         }
5811         mouseMotionListener = AWTEventMulticaster.add(mouseMotionListener,l);
5812         newEventsOnly = true;
5813 
5814         // if this is a lightweight component, enable mouse events
5815         // in the native container.
5816         if (peer instanceof LightweightPeer) {
5817             parent.proxyEnableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
5818         }
5819     }
5820 
5821     /**
5822      * Removes the specified mouse motion listener so that it no longer
5823      * receives mouse motion events from this component. This method performs
5824      * no function, nor does it throw an exception, if the listener
5825      * specified by the argument was not previously added to this component.
5826      * If listener {@code l} is {@code null},
5827      * no exception is thrown and no action is performed.
5828      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5829      * >AWT Threading Issues</a> for details on AWT's threading model.
5830      *
5831      * @param    l   the mouse motion listener
5832      * @see      java.awt.event.MouseEvent
5833      * @see      java.awt.event.MouseMotionListener
5834      * @see      #addMouseMotionListener
5835      * @see      #getMouseMotionListeners
5836      * @since    1.1
5837      */
5838     public synchronized void removeMouseMotionListener(MouseMotionListener l) {
5839         if (l == null) {
5840             return;
5841         }
5842         mouseMotionListener = AWTEventMulticaster.remove(mouseMotionListener, l);
5843     }
5844 
5845     /**
5846      * Returns an array of all the mouse motion listeners
5847      * registered on this component.
5848      *
5849      * @return all of this component's {@code MouseMotionListener}s
5850      *         or an empty array if no mouse motion
5851      *         listeners are currently registered
5852      *
5853      * @see      #addMouseMotionListener
5854      * @see      #removeMouseMotionListener
5855      * @since    1.4
5856      */
5857     public synchronized MouseMotionListener[] getMouseMotionListeners() {
5858         return getListeners(MouseMotionListener.class);
5859     }
5860 
5861     /**
5862      * Adds the specified mouse wheel listener to receive mouse wheel events
5863      * from this component.  Containers also receive mouse wheel events from
5864      * sub-components.
5865      * <p>
5866      * For information on how mouse wheel events are dispatched, see
5867      * the class description for {@link MouseWheelEvent}.
5868      * <p>
5869      * If l is {@code null}, no exception is thrown and no
5870      * action is performed.
5871      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5872      * >AWT Threading Issues</a> for details on AWT's threading model.
5873      *
5874      * @param    l   the mouse wheel listener
5875      * @see      java.awt.event.MouseWheelEvent
5876      * @see      java.awt.event.MouseWheelListener
5877      * @see      #removeMouseWheelListener
5878      * @see      #getMouseWheelListeners
5879      * @since    1.4
5880      */
5881     public synchronized void addMouseWheelListener(MouseWheelListener l) {
5882         if (l == null) {
5883             return;
5884         }
5885         mouseWheelListener = AWTEventMulticaster.add(mouseWheelListener,l);
5886         newEventsOnly = true;
5887 
5888         // if this is a lightweight component, enable mouse events
5889         // in the native container.
5890         if (peer instanceof LightweightPeer) {
5891             parent.proxyEnableEvents(AWTEvent.MOUSE_WHEEL_EVENT_MASK);
5892         }
5893     }
5894 
5895     /**
5896      * Removes the specified mouse wheel listener so that it no longer
5897      * receives mouse wheel events from this component. This method performs
5898      * no function, nor does it throw an exception, if the listener
5899      * specified by the argument was not previously added to this component.
5900      * If l is null, no exception is thrown and no action is performed.
5901      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5902      * >AWT Threading Issues</a> for details on AWT's threading model.
5903      *
5904      * @param    l   the mouse wheel listener.
5905      * @see      java.awt.event.MouseWheelEvent
5906      * @see      java.awt.event.MouseWheelListener
5907      * @see      #addMouseWheelListener
5908      * @see      #getMouseWheelListeners
5909      * @since    1.4
5910      */
5911     public synchronized void removeMouseWheelListener(MouseWheelListener l) {
5912         if (l == null) {
5913             return;
5914         }
5915         mouseWheelListener = AWTEventMulticaster.remove(mouseWheelListener, l);
5916     }
5917 
5918     /**
5919      * Returns an array of all the mouse wheel listeners
5920      * registered on this component.
5921      *
5922      * @return all of this component's {@code MouseWheelListener}s
5923      *         or an empty array if no mouse wheel
5924      *         listeners are currently registered
5925      *
5926      * @see      #addMouseWheelListener
5927      * @see      #removeMouseWheelListener
5928      * @since    1.4
5929      */
5930     public synchronized MouseWheelListener[] getMouseWheelListeners() {
5931         return getListeners(MouseWheelListener.class);
5932     }
5933 
5934     /**
5935      * Adds the specified input method listener to receive
5936      * input method events from this component. A component will
5937      * only receive input method events from input methods
5938      * if it also overrides {@code getInputMethodRequests} to return an
5939      * {@code InputMethodRequests} instance.
5940      * If listener {@code l} is {@code null},
5941      * no exception is thrown and no action is performed.
5942      * <p>Refer to <a href="{@docRoot}/java/awt/doc-files/AWTThreadIssues.html#ListenersThreads"
5943      * >AWT Threading Issues</a> for details on AWT's threading model.
5944      *
5945      * @param    l   the input method listener
5946      * @see      java.awt.event.InputMethodEvent
5947      * @see      java.awt.event.InputMethodListener
5948      * @see      #removeInputMethodListener
5949      * @see      #getInputMethodListeners
5950      * @see      #getInputMethodRequests
5951      * @since    1.2
5952      */
5953     public synchronized void addInputMethodListener(InputMethodListener l) {
5954         if (l == null) {
5955             return;
5956         }
5957         inputMethodListener = AWTEventMulticaster.add(inputMethodListener, l);
5958         newEventsOnly = true;
5959     }
5960 
5961     /**
5962      * Removes the specified input method listener so that it no longer
5963      * receives input method events from this component. This method performs
5964      * no function, nor does it throw an exception, if the listener
5965      * specified by the argument was not previously added to this component.
5966      * If listener {@code l} is {@code null},
5967      * no exception is thrown and no action is performed.
5968      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5969      * >AWT Threading Issues</a> for details on AWT's threading model.
5970      *
5971      * @param    l   the input method listener
5972      * @see      java.awt.event.InputMethodEvent
5973      * @see      java.awt.event.InputMethodListener
5974      * @see      #addInputMethodListener
5975      * @see      #getInputMethodListeners
5976      * @since    1.2
5977      */
5978     public synchronized void removeInputMethodListener(InputMethodListener l) {
5979         if (l == null) {
5980             return;
5981         }
5982         inputMethodListener = AWTEventMulticaster.remove(inputMethodListener, l);
5983     }
5984 
5985     /**
5986      * Returns an array of all the input method listeners
5987      * registered on this component.
5988      *
5989      * @return all of this component's {@code InputMethodListener}s
5990      *         or an empty array if no input method
5991      *         listeners are currently registered
5992      *
5993      * @see      #addInputMethodListener
5994      * @see      #removeInputMethodListener
5995      * @since    1.4
5996      */
5997     public synchronized InputMethodListener[] getInputMethodListeners() {
5998         return getListeners(InputMethodListener.class);
5999     }
6000 
6001     /**
6002      * Returns an array of all the objects currently registered
6003      * as <code><em>Foo</em>Listener</code>s
6004      * upon this {@code Component}.
6005      * <code><em>Foo</em>Listener</code>s are registered using the
6006      * <code>add<em>Foo</em>Listener</code> method.
6007      *
6008      * <p>
6009      * You can specify the {@code listenerType} argument
6010      * with a class literal, such as
6011      * <code><em>Foo</em>Listener.class</code>.
6012      * For example, you can query a
6013      * {@code Component c}
6014      * for its mouse listeners with the following code:
6015      *
6016      * <pre>MouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class));</pre>
6017      *
6018      * If no such listeners exist, this method returns an empty array.
6019      *
6020      * @param <T> the type of the listeners
6021      * @param listenerType the type of listeners requested; this parameter
6022      *          should specify an interface that descends from
6023      *          {@code java.util.EventListener}
6024      * @return an array of all objects registered as
6025      *          <code><em>Foo</em>Listener</code>s on this component,
6026      *          or an empty array if no such listeners have been added
6027      * @exception ClassCastException if {@code listenerType}
6028      *          doesn't specify a class or interface that implements
6029      *          {@code java.util.EventListener}
6030      * @throws NullPointerException if {@code listenerType} is {@code null}
6031      * @see #getComponentListeners
6032      * @see #getFocusListeners
6033      * @see #getHierarchyListeners
6034      * @see #getHierarchyBoundsListeners
6035      * @see #getKeyListeners
6036      * @see #getMouseListeners
6037      * @see #getMouseMotionListeners
6038      * @see #getMouseWheelListeners
6039      * @see #getInputMethodListeners
6040      * @see #getPropertyChangeListeners
6041      *
6042      * @since 1.3
6043      */
6044     @SuppressWarnings("unchecked")
6045     public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
6046         EventListener l = null;
6047         if  (listenerType == ComponentListener.class) {
6048             l = componentListener;
6049         } else if (listenerType == FocusListener.class) {
6050             l = focusListener;
6051         } else if (listenerType == HierarchyListener.class) {
6052             l = hierarchyListener;
6053         } else if (listenerType == HierarchyBoundsListener.class) {
6054             l = hierarchyBoundsListener;
6055         } else if (listenerType == KeyListener.class) {
6056             l = keyListener;
6057         } else if (listenerType == MouseListener.class) {
6058             l = mouseListener;
6059         } else if (listenerType == MouseMotionListener.class) {
6060             l = mouseMotionListener;
6061         } else if (listenerType == MouseWheelListener.class) {
6062             l = mouseWheelListener;
6063         } else if (listenerType == InputMethodListener.class) {
6064             l = inputMethodListener;
6065         } else if (listenerType == PropertyChangeListener.class) {
6066             return (T[])getPropertyChangeListeners();
6067         }
6068         return AWTEventMulticaster.getListeners(l, listenerType);
6069     }
6070 
6071     /**
6072      * Gets the input method request handler which supports
6073      * requests from input methods for this component. A component
6074      * that supports on-the-spot text input must override this
6075      * method to return an {@code InputMethodRequests} instance.
6076      * At the same time, it also has to handle input method events.
6077      *
6078      * @return the input method request handler for this component,
6079      *          {@code null} by default
6080      * @see #addInputMethodListener
6081      * @since 1.2
6082      */
6083     public InputMethodRequests getInputMethodRequests() {
6084         return null;
6085     }
6086 
6087     /**
6088      * Gets the input context used by this component for handling
6089      * the communication with input methods when text is entered
6090      * in this component. By default, the input context used for
6091      * the parent component is returned. Components may
6092      * override this to return a private input context.
6093      *
6094      * @return the input context used by this component;
6095      *          {@code null} if no context can be determined
6096      * @since 1.2
6097      */
6098     public InputContext getInputContext() {
6099         Container parent = this.parent;
6100         if (parent == null) {
6101             return null;
6102         } else {
6103             return parent.getInputContext();
6104         }
6105     }
6106 
6107     /**
6108      * Enables the events defined by the specified event mask parameter
6109      * to be delivered to this component.
6110      * <p>
6111      * Event types are automatically enabled when a listener for
6112      * that event type is added to the component.
6113      * <p>
6114      * This method only needs to be invoked by subclasses of
6115      * {@code Component} which desire to have the specified event
6116      * types delivered to {@code processEvent} regardless of whether
6117      * or not a listener is registered.
6118      * @param      eventsToEnable   the event mask defining the event types
6119      * @see        #processEvent
6120      * @see        #disableEvents
6121      * @see        AWTEvent
6122      * @since      1.1
6123      */
6124     protected final void enableEvents(long eventsToEnable) {
6125         long notifyAncestors = 0;
6126         synchronized (this) {
6127             if ((eventsToEnable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 &&
6128                 hierarchyListener == null &&
6129                 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0) {
6130                 notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK;
6131             }
6132             if ((eventsToEnable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 &&
6133                 hierarchyBoundsListener == null &&
6134                 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0) {
6135                 notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK;
6136             }
6137             eventMask |= eventsToEnable;
6138             newEventsOnly = true;
6139         }
6140 
6141         // if this is a lightweight component, enable mouse events
6142         // in the native container.
6143         if (peer instanceof LightweightPeer) {
6144             parent.proxyEnableEvents(eventMask);
6145         }
6146         if (notifyAncestors != 0) {
6147             synchronized (getTreeLock()) {
6148                 adjustListeningChildrenOnParent(notifyAncestors, 1);
6149             }
6150         }
6151     }
6152 
6153     /**
6154      * Disables the events defined by the specified event mask parameter
6155      * from being delivered to this component.
6156      * @param      eventsToDisable   the event mask defining the event types
6157      * @see        #enableEvents
6158      * @since      1.1
6159      */
6160     protected final void disableEvents(long eventsToDisable) {
6161         long notifyAncestors = 0;
6162         synchronized (this) {
6163             if ((eventsToDisable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 &&
6164                 hierarchyListener == null &&
6165                 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0) {
6166                 notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK;
6167             }
6168             if ((eventsToDisable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK)!=0 &&
6169                 hierarchyBoundsListener == null &&
6170                 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0) {
6171                 notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK;
6172             }
6173             eventMask &= ~eventsToDisable;
6174         }
6175         if (notifyAncestors != 0) {
6176             synchronized (getTreeLock()) {
6177                 adjustListeningChildrenOnParent(notifyAncestors, -1);
6178             }
6179         }
6180     }
6181 
6182     transient sun.awt.EventQueueItem[] eventCache;
6183 
6184     /**
6185      * @see #isCoalescingEnabled
6186      * @see #checkCoalescing
6187      */
6188     private transient boolean coalescingEnabled = checkCoalescing();
6189 
6190     /**
6191      * Weak map of known coalesceEvent overriders.
6192      * Value indicates whether overriden.
6193      * Bootstrap classes are not included.
6194      */
6195     private static final Map<Class<?>, Boolean> coalesceMap =
6196         new java.util.WeakHashMap<Class<?>, Boolean>();
6197 
6198     /**
6199      * Indicates whether this class overrides coalesceEvents.
6200      * It is assumed that all classes that are loaded from the bootstrap
6201      *   do not.
6202      * The bootstrap class loader is assumed to be represented by null.
6203      * We do not check that the method really overrides
6204      *   (it might be static, private or package private).
6205      */
6206      private boolean checkCoalescing() {
6207          if (getClass().getClassLoader()==null) {
6208              return false;
6209          }
6210          final Class<? extends Component> clazz = getClass();
6211          synchronized (coalesceMap) {
6212              // Check cache.
6213              Boolean value = coalesceMap.get(clazz);
6214              if (value != null) {
6215                  return value;
6216              }
6217 
6218              // Need to check non-bootstraps.
6219              Boolean enabled = java.security.AccessController.doPrivileged(
6220                  new java.security.PrivilegedAction<Boolean>() {
6221                      public Boolean run() {
6222                          return isCoalesceEventsOverriden(clazz);
6223                      }
6224                  }
6225                  );
6226              coalesceMap.put(clazz, enabled);
6227              return enabled;
6228          }
6229      }
6230 
6231     /**
6232      * Parameter types of coalesceEvents(AWTEvent,AWTEVent).
6233      */
6234     private static final Class<?>[] coalesceEventsParams = {
6235         AWTEvent.class, AWTEvent.class
6236     };
6237 
6238     /**
6239      * Indicates whether a class or its superclasses override coalesceEvents.
6240      * Must be called with lock on coalesceMap and privileged.
6241      * @see #checkCoalescing
6242      */
6243     private static boolean isCoalesceEventsOverriden(Class<?> clazz) {
6244         assert Thread.holdsLock(coalesceMap);
6245 
6246         // First check superclass - we may not need to bother ourselves.
6247         Class<?> superclass = clazz.getSuperclass();
6248         if (superclass == null) {
6249             // Only occurs on implementations that
6250             //   do not use null to represent the bootstrap class loader.
6251             return false;
6252         }
6253         if (superclass.getClassLoader() != null) {
6254             Boolean value = coalesceMap.get(superclass);
6255             if (value == null) {
6256                 // Not done already - recurse.
6257                 if (isCoalesceEventsOverriden(superclass)) {
6258                     coalesceMap.put(superclass, true);
6259                     return true;
6260                 }
6261             } else if (value) {
6262                 return true;
6263             }
6264         }
6265 
6266         try {
6267             // Throws if not overriden.
6268             clazz.getDeclaredMethod(
6269                 "coalesceEvents", coalesceEventsParams
6270                 );
6271             return true;
6272         } catch (NoSuchMethodException e) {
6273             // Not present in this class.
6274             return false;
6275         }
6276     }
6277 
6278     /**
6279      * Indicates whether coalesceEvents may do something.
6280      */
6281     final boolean isCoalescingEnabled() {
6282         return coalescingEnabled;
6283      }
6284 
6285 
6286     /**
6287      * Potentially coalesce an event being posted with an existing
6288      * event.  This method is called by {@code EventQueue.postEvent}
6289      * if an event with the same ID as the event to be posted is found in
6290      * the queue (both events must have this component as their source).
6291      * This method either returns a coalesced event which replaces
6292      * the existing event (and the new event is then discarded), or
6293      * {@code null} to indicate that no combining should be done
6294      * (add the second event to the end of the queue).  Either event
6295      * parameter may be modified and returned, as the other one is discarded
6296      * unless {@code null} is returned.
6297      * <p>
6298      * This implementation of {@code coalesceEvents} coalesces
6299      * two event types: mouse move (and drag) events,
6300      * and paint (and update) events.
6301      * For mouse move events the last event is always returned, causing
6302      * intermediate moves to be discarded.  For paint events, the new
6303      * event is coalesced into a complex {@code RepaintArea} in the peer.
6304      * The new {@code AWTEvent} is always returned.
6305      *
6306      * @param  existingEvent  the event already on the {@code EventQueue}
6307      * @param  newEvent       the event being posted to the
6308      *          {@code EventQueue}
6309      * @return a coalesced event, or {@code null} indicating that no
6310      *          coalescing was done
6311      */
6312     protected AWTEvent coalesceEvents(AWTEvent existingEvent,
6313                                       AWTEvent newEvent) {
6314         return null;
6315     }
6316 
6317     /**
6318      * Processes events occurring on this component. By default this
6319      * method calls the appropriate
6320      * <code>process&lt;event&nbsp;type&gt;Event</code>
6321      * method for the given class of event.
6322      * <p>Note that if the event parameter is {@code null}
6323      * the behavior is unspecified and may result in an
6324      * exception.
6325      *
6326      * @param     e the event
6327      * @see       #processComponentEvent
6328      * @see       #processFocusEvent
6329      * @see       #processKeyEvent
6330      * @see       #processMouseEvent
6331      * @see       #processMouseMotionEvent
6332      * @see       #processInputMethodEvent
6333      * @see       #processHierarchyEvent
6334      * @see       #processMouseWheelEvent
6335      * @since     1.1
6336      */
6337     protected void processEvent(AWTEvent e) {
6338         if (e instanceof FocusEvent) {
6339             processFocusEvent((FocusEvent)e);
6340 
6341         } else if (e instanceof MouseEvent) {
6342             switch(e.getID()) {
6343               case MouseEvent.MOUSE_PRESSED:
6344               case MouseEvent.MOUSE_RELEASED:
6345               case MouseEvent.MOUSE_CLICKED:
6346               case MouseEvent.MOUSE_ENTERED:
6347               case MouseEvent.MOUSE_EXITED:
6348                   processMouseEvent((MouseEvent)e);
6349                   break;
6350               case MouseEvent.MOUSE_MOVED:
6351               case MouseEvent.MOUSE_DRAGGED:
6352                   processMouseMotionEvent((MouseEvent)e);
6353                   break;
6354               case MouseEvent.MOUSE_WHEEL:
6355                   processMouseWheelEvent((MouseWheelEvent)e);
6356                   break;
6357             }
6358 
6359         } else if (e instanceof KeyEvent) {
6360             processKeyEvent((KeyEvent)e);
6361 
6362         } else if (e instanceof ComponentEvent) {
6363             processComponentEvent((ComponentEvent)e);
6364         } else if (e instanceof InputMethodEvent) {
6365             processInputMethodEvent((InputMethodEvent)e);
6366         } else if (e instanceof HierarchyEvent) {
6367             switch (e.getID()) {
6368               case HierarchyEvent.HIERARCHY_CHANGED:
6369                   processHierarchyEvent((HierarchyEvent)e);
6370                   break;
6371               case HierarchyEvent.ANCESTOR_MOVED:
6372               case HierarchyEvent.ANCESTOR_RESIZED:
6373                   processHierarchyBoundsEvent((HierarchyEvent)e);
6374                   break;
6375             }
6376         }
6377     }
6378 
6379     /**
6380      * Processes component events occurring on this component by
6381      * dispatching them to any registered
6382      * {@code ComponentListener} objects.
6383      * <p>
6384      * This method is not called unless component events are
6385      * enabled for this component. Component events are enabled
6386      * when one of the following occurs:
6387      * <ul>
6388      * <li>A {@code ComponentListener} object is registered
6389      * via {@code addComponentListener}.
6390      * <li>Component events are enabled via {@code enableEvents}.
6391      * </ul>
6392      * <p>Note that if the event parameter is {@code null}
6393      * the behavior is unspecified and may result in an
6394      * exception.
6395      *
6396      * @param       e the component event
6397      * @see         java.awt.event.ComponentEvent
6398      * @see         java.awt.event.ComponentListener
6399      * @see         #addComponentListener
6400      * @see         #enableEvents
6401      * @since       1.1
6402      */
6403     protected void processComponentEvent(ComponentEvent e) {
6404         ComponentListener listener = componentListener;
6405         if (listener != null) {
6406             int id = e.getID();
6407             switch(id) {
6408               case ComponentEvent.COMPONENT_RESIZED:
6409                   listener.componentResized(e);
6410                   break;
6411               case ComponentEvent.COMPONENT_MOVED:
6412                   listener.componentMoved(e);
6413                   break;
6414               case ComponentEvent.COMPONENT_SHOWN:
6415                   listener.componentShown(e);
6416                   break;
6417               case ComponentEvent.COMPONENT_HIDDEN:
6418                   listener.componentHidden(e);
6419                   break;
6420             }
6421         }
6422     }
6423 
6424     /**
6425      * Processes focus events occurring on this component by
6426      * dispatching them to any registered
6427      * {@code FocusListener} objects.
6428      * <p>
6429      * This method is not called unless focus events are
6430      * enabled for this component. Focus events are enabled
6431      * when one of the following occurs:
6432      * <ul>
6433      * <li>A {@code FocusListener} object is registered
6434      * via {@code addFocusListener}.
6435      * <li>Focus events are enabled via {@code enableEvents}.
6436      * </ul>
6437      * <p>
6438      * If focus events are enabled for a {@code Component},
6439      * the current {@code KeyboardFocusManager} determines
6440      * whether or not a focus event should be dispatched to
6441      * registered {@code FocusListener} objects.  If the
6442      * events are to be dispatched, the {@code KeyboardFocusManager}
6443      * calls the {@code Component}'s {@code dispatchEvent}
6444      * method, which results in a call to the {@code Component}'s
6445      * {@code processFocusEvent} method.
6446      * <p>
6447      * If focus events are enabled for a {@code Component}, calling
6448      * the {@code Component}'s {@code dispatchEvent} method
6449      * with a {@code FocusEvent} as the argument will result in a
6450      * call to the {@code Component}'s {@code processFocusEvent}
6451      * method regardless of the current {@code KeyboardFocusManager}.
6452      *
6453      * <p>Note that if the event parameter is {@code null}
6454      * the behavior is unspecified and may result in an
6455      * exception.
6456      *
6457      * @param       e the focus event
6458      * @see         java.awt.event.FocusEvent
6459      * @see         java.awt.event.FocusListener
6460      * @see         java.awt.KeyboardFocusManager
6461      * @see         #addFocusListener
6462      * @see         #enableEvents
6463      * @see         #dispatchEvent
6464      * @since       1.1
6465      */
6466     protected void processFocusEvent(FocusEvent e) {
6467         FocusListener listener = focusListener;
6468         if (listener != null) {
6469             int id = e.getID();
6470             switch(id) {
6471               case FocusEvent.FOCUS_GAINED:
6472                   listener.focusGained(e);
6473                   break;
6474               case FocusEvent.FOCUS_LOST:
6475                   listener.focusLost(e);
6476                   break;
6477             }
6478         }
6479     }
6480 
6481     /**
6482      * Processes key events occurring on this component by
6483      * dispatching them to any registered
6484      * {@code KeyListener} objects.
6485      * <p>
6486      * This method is not called unless key events are
6487      * enabled for this component. Key events are enabled
6488      * when one of the following occurs:
6489      * <ul>
6490      * <li>A {@code KeyListener} object is registered
6491      * via {@code addKeyListener}.
6492      * <li>Key events are enabled via {@code enableEvents}.
6493      * </ul>
6494      *
6495      * <p>
6496      * If key events are enabled for a {@code Component},
6497      * the current {@code KeyboardFocusManager} determines
6498      * whether or not a key event should be dispatched to
6499      * registered {@code KeyListener} objects.  The
6500      * {@code DefaultKeyboardFocusManager} will not dispatch
6501      * key events to a {@code Component} that is not the focus
6502      * owner or is not showing.
6503      * <p>
6504      * As of J2SE 1.4, {@code KeyEvent}s are redirected to
6505      * the focus owner. Please see the
6506      * <a href="doc-files/FocusSpec.html">Focus Specification</a>
6507      * for further information.
6508      * <p>
6509      * Calling a {@code Component}'s {@code dispatchEvent}
6510      * method with a {@code KeyEvent} as the argument will
6511      * result in a call to the {@code Component}'s
6512      * {@code processKeyEvent} method regardless of the
6513      * current {@code KeyboardFocusManager} as long as the
6514      * component is showing, focused, and enabled, and key events
6515      * are enabled on it.
6516      * <p>If the event parameter is {@code null}
6517      * the behavior is unspecified and may result in an
6518      * exception.
6519      *
6520      * @param       e the key event
6521      * @see         java.awt.event.KeyEvent
6522      * @see         java.awt.event.KeyListener
6523      * @see         java.awt.KeyboardFocusManager
6524      * @see         java.awt.DefaultKeyboardFocusManager
6525      * @see         #processEvent
6526      * @see         #dispatchEvent
6527      * @see         #addKeyListener
6528      * @see         #enableEvents
6529      * @see         #isShowing
6530      * @since       1.1
6531      */
6532     protected void processKeyEvent(KeyEvent e) {
6533         KeyListener listener = keyListener;
6534         if (listener != null) {
6535             int id = e.getID();
6536             switch(id) {
6537               case KeyEvent.KEY_TYPED:
6538                   listener.keyTyped(e);
6539                   break;
6540               case KeyEvent.KEY_PRESSED:
6541                   listener.keyPressed(e);
6542                   break;
6543               case KeyEvent.KEY_RELEASED:
6544                   listener.keyReleased(e);
6545                   break;
6546             }
6547         }
6548     }
6549 
6550     /**
6551      * Processes mouse events occurring on this component by
6552      * dispatching them to any registered
6553      * {@code MouseListener} objects.
6554      * <p>
6555      * This method is not called unless mouse events are
6556      * enabled for this component. Mouse events are enabled
6557      * when one of the following occurs:
6558      * <ul>
6559      * <li>A {@code MouseListener} object is registered
6560      * via {@code addMouseListener}.
6561      * <li>Mouse events are enabled via {@code enableEvents}.
6562      * </ul>
6563      * <p>Note that if the event parameter is {@code null}
6564      * the behavior is unspecified and may result in an
6565      * exception.
6566      *
6567      * @param       e the mouse event
6568      * @see         java.awt.event.MouseEvent
6569      * @see         java.awt.event.MouseListener
6570      * @see         #addMouseListener
6571      * @see         #enableEvents
6572      * @since       1.1
6573      */
6574     protected void processMouseEvent(MouseEvent e) {
6575         MouseListener listener = mouseListener;
6576         if (listener != null) {
6577             int id = e.getID();
6578             switch(id) {
6579               case MouseEvent.MOUSE_PRESSED:
6580                   listener.mousePressed(e);
6581                   break;
6582               case MouseEvent.MOUSE_RELEASED:
6583                   listener.mouseReleased(e);
6584                   break;
6585               case MouseEvent.MOUSE_CLICKED:
6586                   listener.mouseClicked(e);
6587                   break;
6588               case MouseEvent.MOUSE_EXITED:
6589                   listener.mouseExited(e);
6590                   break;
6591               case MouseEvent.MOUSE_ENTERED:
6592                   listener.mouseEntered(e);
6593                   break;
6594             }
6595         }
6596     }
6597 
6598     /**
6599      * Processes mouse motion events occurring on this component by
6600      * dispatching them to any registered
6601      * {@code MouseMotionListener} objects.
6602      * <p>
6603      * This method is not called unless mouse motion events are
6604      * enabled for this component. Mouse motion events are enabled
6605      * when one of the following occurs:
6606      * <ul>
6607      * <li>A {@code MouseMotionListener} object is registered
6608      * via {@code addMouseMotionListener}.
6609      * <li>Mouse motion events are enabled via {@code enableEvents}.
6610      * </ul>
6611      * <p>Note that if the event parameter is {@code null}
6612      * the behavior is unspecified and may result in an
6613      * exception.
6614      *
6615      * @param       e the mouse motion event
6616      * @see         java.awt.event.MouseEvent
6617      * @see         java.awt.event.MouseMotionListener
6618      * @see         #addMouseMotionListener
6619      * @see         #enableEvents
6620      * @since       1.1
6621      */
6622     protected void processMouseMotionEvent(MouseEvent e) {
6623         MouseMotionListener listener = mouseMotionListener;
6624         if (listener != null) {
6625             int id = e.getID();
6626             switch(id) {
6627               case MouseEvent.MOUSE_MOVED:
6628                   listener.mouseMoved(e);
6629                   break;
6630               case MouseEvent.MOUSE_DRAGGED:
6631                   listener.mouseDragged(e);
6632                   break;
6633             }
6634         }
6635     }
6636 
6637     /**
6638      * Processes mouse wheel events occurring on this component by
6639      * dispatching them to any registered
6640      * {@code MouseWheelListener} objects.
6641      * <p>
6642      * This method is not called unless mouse wheel events are
6643      * enabled for this component. Mouse wheel events are enabled
6644      * when one of the following occurs:
6645      * <ul>
6646      * <li>A {@code MouseWheelListener} object is registered
6647      * via {@code addMouseWheelListener}.
6648      * <li>Mouse wheel events are enabled via {@code enableEvents}.
6649      * </ul>
6650      * <p>
6651      * For information on how mouse wheel events are dispatched, see
6652      * the class description for {@link MouseWheelEvent}.
6653      * <p>
6654      * Note that if the event parameter is {@code null}
6655      * the behavior is unspecified and may result in an
6656      * exception.
6657      *
6658      * @param       e the mouse wheel event
6659      * @see         java.awt.event.MouseWheelEvent
6660      * @see         java.awt.event.MouseWheelListener
6661      * @see         #addMouseWheelListener
6662      * @see         #enableEvents
6663      * @since       1.4
6664      */
6665     protected void processMouseWheelEvent(MouseWheelEvent e) {
6666         MouseWheelListener listener = mouseWheelListener;
6667         if (listener != null) {
6668             int id = e.getID();
6669             switch(id) {
6670               case MouseEvent.MOUSE_WHEEL:
6671                   listener.mouseWheelMoved(e);
6672                   break;
6673             }
6674         }
6675     }
6676 
6677     boolean postsOldMouseEvents() {
6678         return false;
6679     }
6680 
6681     /**
6682      * Processes input method events occurring on this component by
6683      * dispatching them to any registered
6684      * {@code InputMethodListener} objects.
6685      * <p>
6686      * This method is not called unless input method events
6687      * are enabled for this component. Input method events are enabled
6688      * when one of the following occurs:
6689      * <ul>
6690      * <li>An {@code InputMethodListener} object is registered
6691      * via {@code addInputMethodListener}.
6692      * <li>Input method events are enabled via {@code enableEvents}.
6693      * </ul>
6694      * <p>Note that if the event parameter is {@code null}
6695      * the behavior is unspecified and may result in an
6696      * exception.
6697      *
6698      * @param       e the input method event
6699      * @see         java.awt.event.InputMethodEvent
6700      * @see         java.awt.event.InputMethodListener
6701      * @see         #addInputMethodListener
6702      * @see         #enableEvents
6703      * @since       1.2
6704      */
6705     protected void processInputMethodEvent(InputMethodEvent e) {
6706         InputMethodListener listener = inputMethodListener;
6707         if (listener != null) {
6708             int id = e.getID();
6709             switch (id) {
6710               case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED:
6711                   listener.inputMethodTextChanged(e);
6712                   break;
6713               case InputMethodEvent.CARET_POSITION_CHANGED:
6714                   listener.caretPositionChanged(e);
6715                   break;
6716             }
6717         }
6718     }
6719 
6720     /**
6721      * Processes hierarchy events occurring on this component by
6722      * dispatching them to any registered
6723      * {@code HierarchyListener} objects.
6724      * <p>
6725      * This method is not called unless hierarchy events
6726      * are enabled for this component. Hierarchy events are enabled
6727      * when one of the following occurs:
6728      * <ul>
6729      * <li>An {@code HierarchyListener} object is registered
6730      * via {@code addHierarchyListener}.
6731      * <li>Hierarchy events are enabled via {@code enableEvents}.
6732      * </ul>
6733      * <p>Note that if the event parameter is {@code null}
6734      * the behavior is unspecified and may result in an
6735      * exception.
6736      *
6737      * @param       e the hierarchy event
6738      * @see         java.awt.event.HierarchyEvent
6739      * @see         java.awt.event.HierarchyListener
6740      * @see         #addHierarchyListener
6741      * @see         #enableEvents
6742      * @since       1.3
6743      */
6744     protected void processHierarchyEvent(HierarchyEvent e) {
6745         HierarchyListener listener = hierarchyListener;
6746         if (listener != null) {
6747             int id = e.getID();
6748             switch (id) {
6749               case HierarchyEvent.HIERARCHY_CHANGED:
6750                   listener.hierarchyChanged(e);
6751                   break;
6752             }
6753         }
6754     }
6755 
6756     /**
6757      * Processes hierarchy bounds events occurring on this component by
6758      * dispatching them to any registered
6759      * {@code HierarchyBoundsListener} objects.
6760      * <p>
6761      * This method is not called unless hierarchy bounds events
6762      * are enabled for this component. Hierarchy bounds events are enabled
6763      * when one of the following occurs:
6764      * <ul>
6765      * <li>An {@code HierarchyBoundsListener} object is registered
6766      * via {@code addHierarchyBoundsListener}.
6767      * <li>Hierarchy bounds events are enabled via {@code enableEvents}.
6768      * </ul>
6769      * <p>Note that if the event parameter is {@code null}
6770      * the behavior is unspecified and may result in an
6771      * exception.
6772      *
6773      * @param       e the hierarchy event
6774      * @see         java.awt.event.HierarchyEvent
6775      * @see         java.awt.event.HierarchyBoundsListener
6776      * @see         #addHierarchyBoundsListener
6777      * @see         #enableEvents
6778      * @since       1.3
6779      */
6780     protected void processHierarchyBoundsEvent(HierarchyEvent e) {
6781         HierarchyBoundsListener listener = hierarchyBoundsListener;
6782         if (listener != null) {
6783             int id = e.getID();
6784             switch (id) {
6785               case HierarchyEvent.ANCESTOR_MOVED:
6786                   listener.ancestorMoved(e);
6787                   break;
6788               case HierarchyEvent.ANCESTOR_RESIZED:
6789                   listener.ancestorResized(e);
6790                   break;
6791             }
6792         }
6793     }
6794 
6795     /**
6796      * @param  evt the event to handle
6797      * @return {@code true} if the event was handled, {@code false} otherwise
6798      * @deprecated As of JDK version 1.1
6799      * replaced by processEvent(AWTEvent).
6800      */
6801     @Deprecated
6802     public boolean handleEvent(Event evt) {
6803         switch (evt.id) {
6804           case Event.MOUSE_ENTER:
6805               return mouseEnter(evt, evt.x, evt.y);
6806 
6807           case Event.MOUSE_EXIT:
6808               return mouseExit(evt, evt.x, evt.y);
6809 
6810           case Event.MOUSE_MOVE:
6811               return mouseMove(evt, evt.x, evt.y);
6812 
6813           case Event.MOUSE_DOWN:
6814               return mouseDown(evt, evt.x, evt.y);
6815 
6816           case Event.MOUSE_DRAG:
6817               return mouseDrag(evt, evt.x, evt.y);
6818 
6819           case Event.MOUSE_UP:
6820               return mouseUp(evt, evt.x, evt.y);
6821 
6822           case Event.KEY_PRESS:
6823           case Event.KEY_ACTION:
6824               return keyDown(evt, evt.key);
6825 
6826           case Event.KEY_RELEASE:
6827           case Event.KEY_ACTION_RELEASE:
6828               return keyUp(evt, evt.key);
6829 
6830           case Event.ACTION_EVENT:
6831               return action(evt, evt.arg);
6832           case Event.GOT_FOCUS:
6833               return gotFocus(evt, evt.arg);
6834           case Event.LOST_FOCUS:
6835               return lostFocus(evt, evt.arg);
6836         }
6837         return false;
6838     }
6839 
6840     /**
6841      * @param  evt the event to handle
6842      * @param  x the x coordinate
6843      * @param  y the y coordinate
6844      * @return {@code false}
6845      * @deprecated As of JDK version 1.1,
6846      * replaced by processMouseEvent(MouseEvent).
6847      */
6848     @Deprecated
6849     public boolean mouseDown(Event evt, int x, int y) {
6850         return false;
6851     }
6852 
6853     /**
6854      * @param  evt the event to handle
6855      * @param  x the x coordinate
6856      * @param  y the y coordinate
6857      * @return {@code false}
6858      * @deprecated As of JDK version 1.1,
6859      * replaced by processMouseMotionEvent(MouseEvent).
6860      */
6861     @Deprecated
6862     public boolean mouseDrag(Event evt, int x, int y) {
6863         return false;
6864     }
6865 
6866     /**
6867      * @param  evt the event to handle
6868      * @param  x the x coordinate
6869      * @param  y the y coordinate
6870      * @return {@code false}
6871      * @deprecated As of JDK version 1.1,
6872      * replaced by processMouseEvent(MouseEvent).
6873      */
6874     @Deprecated
6875     public boolean mouseUp(Event evt, int x, int y) {
6876         return false;
6877     }
6878 
6879     /**
6880      * @param  evt the event to handle
6881      * @param  x the x coordinate
6882      * @param  y the y coordinate
6883      * @return {@code false}
6884      * @deprecated As of JDK version 1.1,
6885      * replaced by processMouseMotionEvent(MouseEvent).
6886      */
6887     @Deprecated
6888     public boolean mouseMove(Event evt, int x, int y) {
6889         return false;
6890     }
6891 
6892     /**
6893      * @param  evt the event to handle
6894      * @param  x the x coordinate
6895      * @param  y the y coordinate
6896      * @return {@code false}
6897      * @deprecated As of JDK version 1.1,
6898      * replaced by processMouseEvent(MouseEvent).
6899      */
6900     @Deprecated
6901     public boolean mouseEnter(Event evt, int x, int y) {
6902         return false;
6903     }
6904 
6905     /**
6906      * @param  evt the event to handle
6907      * @param  x the x coordinate
6908      * @param  y the y coordinate
6909      * @return {@code false}
6910      * @deprecated As of JDK version 1.1,
6911      * replaced by processMouseEvent(MouseEvent).
6912      */
6913     @Deprecated
6914     public boolean mouseExit(Event evt, int x, int y) {
6915         return false;
6916     }
6917 
6918     /**
6919      * @param  evt the event to handle
6920      * @param  key the key pressed
6921      * @return {@code false}
6922      * @deprecated As of JDK version 1.1,
6923      * replaced by processKeyEvent(KeyEvent).
6924      */
6925     @Deprecated
6926     public boolean keyDown(Event evt, int key) {
6927         return false;
6928     }
6929 
6930     /**
6931      * @param  evt the event to handle
6932      * @param  key the key pressed
6933      * @return {@code false}
6934      * @deprecated As of JDK version 1.1,
6935      * replaced by processKeyEvent(KeyEvent).
6936      */
6937     @Deprecated
6938     public boolean keyUp(Event evt, int key) {
6939         return false;
6940     }
6941 
6942     /**
6943      * @param  evt the event to handle
6944      * @param  what the object acted on
6945      * @return {@code false}
6946      * @deprecated As of JDK version 1.1,
6947      * should register this component as ActionListener on component
6948      * which fires action events.
6949      */
6950     @Deprecated
6951     public boolean action(Event evt, Object what) {
6952         return false;
6953     }
6954 
6955     /**
6956      * Makes this {@code Component} displayable by connecting it to a
6957      * native screen resource.
6958      * This method is called internally by the toolkit and should
6959      * not be called directly by programs.
6960      * <p>
6961      * This method changes layout-related information, and therefore,
6962      * invalidates the component hierarchy.
6963      *
6964      * @see       #isDisplayable
6965      * @see       #removeNotify
6966      * @see #invalidate
6967      * @since 1.0
6968      */
6969     public void addNotify() {
6970         synchronized (getTreeLock()) {
6971             ComponentPeer peer = this.peer;
6972             if (peer == null || peer instanceof LightweightPeer){
6973                 if (peer == null) {
6974                     // Update both the Component's peer variable and the local
6975                     // variable we use for thread safety.
6976                     this.peer = peer = getComponentFactory().createComponent(this);
6977                 }
6978 
6979                 // This is a lightweight component which means it won't be
6980                 // able to get window-related events by itself.  If any
6981                 // have been enabled, then the nearest native container must
6982                 // be enabled.
6983                 if (parent != null) {
6984                     long mask = 0;
6985                     if ((mouseListener != null) || ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0)) {
6986                         mask |= AWTEvent.MOUSE_EVENT_MASK;
6987                     }
6988                     if ((mouseMotionListener != null) ||
6989                         ((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0)) {
6990                         mask |= AWTEvent.MOUSE_MOTION_EVENT_MASK;
6991                     }
6992                     if ((mouseWheelListener != null ) ||
6993                         ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0)) {
6994                         mask |= AWTEvent.MOUSE_WHEEL_EVENT_MASK;
6995                     }
6996                     if (focusListener != null || (eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0) {
6997                         mask |= AWTEvent.FOCUS_EVENT_MASK;
6998                     }
6999                     if (keyListener != null || (eventMask & AWTEvent.KEY_EVENT_MASK) != 0) {
7000                         mask |= AWTEvent.KEY_EVENT_MASK;
7001                     }
7002                     if (mask != 0) {
7003                         parent.proxyEnableEvents(mask);
7004                     }
7005                 }
7006             } else {
7007                 // It's native. If the parent is lightweight it will need some
7008                 // help.
7009                 Container parent = getContainer();
7010                 if (parent != null && parent.isLightweight()) {
7011                     relocateComponent();
7012                     if (!parent.isRecursivelyVisibleUpToHeavyweightContainer())
7013                     {
7014                         peer.setVisible(false);
7015                     }
7016                 }
7017             }
7018             invalidate();
7019 
7020             int npopups = (popups != null? popups.size() : 0);
7021             for (int i = 0 ; i < npopups ; i++) {
7022                 PopupMenu popup = popups.elementAt(i);
7023                 popup.addNotify();
7024             }
7025 
7026             if (dropTarget != null) dropTarget.addNotify();
7027 
7028             peerFont = getFont();
7029 
7030             if (getContainer() != null && !isAddNotifyComplete) {
7031                 getContainer().increaseComponentCount(this);
7032             }
7033 
7034 
7035             // Update stacking order
7036             updateZOrder();
7037 
7038             if (!isAddNotifyComplete) {
7039                 mixOnShowing();
7040             }
7041 
7042             isAddNotifyComplete = true;
7043 
7044             if (hierarchyListener != null ||
7045                 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
7046                 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) {
7047                 HierarchyEvent e =
7048                     new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED,
7049                                        this, parent,
7050                                        HierarchyEvent.DISPLAYABILITY_CHANGED |
7051                                        ((isRecursivelyVisible())
7052                                         ? HierarchyEvent.SHOWING_CHANGED
7053                                         : 0));
7054                 dispatchEvent(e);
7055             }
7056         }
7057     }
7058 
7059     /**
7060      * Makes this {@code Component} undisplayable by destroying it native
7061      * screen resource.
7062      * <p>
7063      * This method is called by the toolkit internally and should
7064      * not be called directly by programs. Code overriding
7065      * this method should call {@code super.removeNotify} as
7066      * the first line of the overriding method.
7067      *
7068      * @see       #isDisplayable
7069      * @see       #addNotify
7070      * @since 1.0
7071      */
7072     public void removeNotify() {
7073         KeyboardFocusManager.clearMostRecentFocusOwner(this);
7074         if (KeyboardFocusManager.getCurrentKeyboardFocusManager().
7075             getPermanentFocusOwner() == this)
7076         {
7077             KeyboardFocusManager.getCurrentKeyboardFocusManager().
7078                 setGlobalPermanentFocusOwner(null);
7079         }
7080 
7081         synchronized (getTreeLock()) {
7082             if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabledFor(this)) {
7083                 transferFocus(true);
7084             }
7085 
7086             if (getContainer() != null && isAddNotifyComplete) {
7087                 getContainer().decreaseComponentCount(this);
7088             }
7089 
7090             int npopups = (popups != null? popups.size() : 0);
7091             for (int i = 0 ; i < npopups ; i++) {
7092                 PopupMenu popup = popups.elementAt(i);
7093                 popup.removeNotify();
7094             }
7095             // If there is any input context for this component, notify
7096             // that this component is being removed. (This has to be done
7097             // before hiding peer.)
7098             if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) {
7099                 InputContext inputContext = getInputContext();
7100                 if (inputContext != null) {
7101                     inputContext.removeNotify(this);
7102                 }
7103             }
7104 
7105             ComponentPeer p = peer;
7106             if (p != null) {
7107                 boolean isLightweight = isLightweight();
7108 
7109                 if (bufferStrategy instanceof FlipBufferStrategy) {
7110                     ((FlipBufferStrategy)bufferStrategy).destroyBuffers();
7111                 }
7112 
7113                 if (dropTarget != null) dropTarget.removeNotify();
7114 
7115                 // Hide peer first to stop system events such as cursor moves.
7116                 if (visible) {
7117                     p.setVisible(false);
7118                 }
7119 
7120                 peer = null; // Stop peer updates.
7121                 peerFont = null;
7122 
7123                 Toolkit.getEventQueue().removeSourceEvents(this, false);
7124                 KeyboardFocusManager.getCurrentKeyboardFocusManager().
7125                     discardKeyEvents(this);
7126 
7127                 p.dispose();
7128 
7129                 mixOnHiding(isLightweight);
7130 
7131                 isAddNotifyComplete = false;
7132                 // Nullifying compoundShape means that the component has normal shape
7133                 // (or has no shape at all).
7134                 this.compoundShape = null;
7135             }
7136 
7137             if (hierarchyListener != null ||
7138                 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
7139                 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) {
7140                 HierarchyEvent e =
7141                     new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED,
7142                                        this, parent,
7143                                        HierarchyEvent.DISPLAYABILITY_CHANGED |
7144                                        ((isRecursivelyVisible())
7145                                         ? HierarchyEvent.SHOWING_CHANGED
7146                                         : 0));
7147                 dispatchEvent(e);
7148             }
7149         }
7150     }
7151 
7152     /**
7153      * @param  evt the event to handle
7154      * @param  what the object focused
7155      * @return  {@code false}
7156      * @deprecated As of JDK version 1.1,
7157      * replaced by processFocusEvent(FocusEvent).
7158      */
7159     @Deprecated
7160     public boolean gotFocus(Event evt, Object what) {
7161         return false;
7162     }
7163 
7164     /**
7165      * @param evt  the event to handle
7166      * @param what the object focused
7167      * @return  {@code false}
7168      * @deprecated As of JDK version 1.1,
7169      * replaced by processFocusEvent(FocusEvent).
7170      */
7171     @Deprecated
7172     public boolean lostFocus(Event evt, Object what) {
7173         return false;
7174     }
7175 
7176     /**
7177      * Returns whether this {@code Component} can become the focus
7178      * owner.
7179      *
7180      * @return {@code true} if this {@code Component} is
7181      * focusable; {@code false} otherwise
7182      * @see #setFocusable
7183      * @since 1.1
7184      * @deprecated As of 1.4, replaced by {@code isFocusable()}.
7185      */
7186     @Deprecated
7187     public boolean isFocusTraversable() {
7188         if (isFocusTraversableOverridden == FOCUS_TRAVERSABLE_UNKNOWN) {
7189             isFocusTraversableOverridden = FOCUS_TRAVERSABLE_DEFAULT;
7190         }
7191         return focusable;
7192     }
7193 
7194     /**
7195      * Returns whether this Component can be focused.
7196      *
7197      * @return {@code true} if this Component is focusable;
7198      *         {@code false} otherwise.
7199      * @see #setFocusable
7200      * @since 1.4
7201      */
7202     public boolean isFocusable() {
7203         return isFocusTraversable();
7204     }
7205 
7206     /**
7207      * Sets the focusable state of this Component to the specified value. This
7208      * value overrides the Component's default focusability.
7209      *
7210      * @param focusable indicates whether this Component is focusable
7211      * @see #isFocusable
7212      * @since 1.4
7213      */
7214     public void setFocusable(boolean focusable) {
7215         boolean oldFocusable;
7216         synchronized (this) {
7217             oldFocusable = this.focusable;
7218             this.focusable = focusable;
7219         }
7220         isFocusTraversableOverridden = FOCUS_TRAVERSABLE_SET;
7221 
7222         firePropertyChange("focusable", oldFocusable, focusable);
7223         if (oldFocusable && !focusable) {
7224             if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabled()) {
7225                 transferFocus(true);
7226             }
7227             KeyboardFocusManager.clearMostRecentFocusOwner(this);
7228         }
7229     }
7230 
7231     final boolean isFocusTraversableOverridden() {
7232         return (isFocusTraversableOverridden != FOCUS_TRAVERSABLE_DEFAULT);
7233     }
7234 
7235     /**
7236      * Sets the focus traversal keys for a given traversal operation for this
7237      * Component.
7238      * <p>
7239      * The default values for a Component's focus traversal keys are
7240      * implementation-dependent. Sun recommends that all implementations for a
7241      * particular native platform use the same default values. The
7242      * recommendations for Windows and Unix are listed below. These
7243      * recommendations are used in the Sun AWT implementations.
7244      *
7245      * <table class="striped">
7246      * <caption>Recommended default values for a Component's focus traversal
7247      * keys</caption>
7248      * <thead>
7249      * <tr>
7250      *    <th>Identifier</th>
7251      *    <th>Meaning</th>
7252      *    <th>Default</th>
7253      * </tr>
7254      * </thead>
7255      * <tbody>
7256      * <tr>
7257      *    <td>KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS</td>
7258      *    <td>Normal forward keyboard traversal</td>
7259      *    <td>TAB on KEY_PRESSED, CTRL-TAB on KEY_PRESSED</td>
7260      * </tr>
7261      * <tr>
7262      *    <td>KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS</td>
7263      *    <td>Normal reverse keyboard traversal</td>
7264      *    <td>SHIFT-TAB on KEY_PRESSED, CTRL-SHIFT-TAB on KEY_PRESSED</td>
7265      * </tr>
7266      * <tr>
7267      *    <td>KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS</td>
7268      *    <td>Go up one focus traversal cycle</td>
7269      *    <td>none</td>
7270      * </tr>
7271      * </tbody>
7272      * </table>
7273      *
7274      * To disable a traversal key, use an empty Set; Collections.EMPTY_SET is
7275      * recommended.
7276      * <p>
7277      * Using the AWTKeyStroke API, client code can specify on which of two
7278      * specific KeyEvents, KEY_PRESSED or KEY_RELEASED, the focus traversal
7279      * operation will occur. Regardless of which KeyEvent is specified,
7280      * however, all KeyEvents related to the focus traversal key, including the
7281      * associated KEY_TYPED event, will be consumed, and will not be dispatched
7282      * to any Component. It is a runtime error to specify a KEY_TYPED event as
7283      * mapping to a focus traversal operation, or to map the same event to
7284      * multiple default focus traversal operations.
7285      * <p>
7286      * If a value of null is specified for the Set, this Component inherits the
7287      * Set from its parent. If all ancestors of this Component have null
7288      * specified for the Set, then the current KeyboardFocusManager's default
7289      * Set is used.
7290      * <p>
7291      * This method may throw a {@code ClassCastException} if any {@code Object}
7292      * in {@code keystrokes} is not an {@code AWTKeyStroke}.
7293      *
7294      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7295      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7296      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7297      * @param keystrokes the Set of AWTKeyStroke for the specified operation
7298      * @see #getFocusTraversalKeys
7299      * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
7300      * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
7301      * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
7302      * @throws IllegalArgumentException if id is not one of
7303      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7304      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7305      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or if keystrokes
7306      *         contains null, or if any keystroke represents a KEY_TYPED event,
7307      *         or if any keystroke already maps to another focus traversal
7308      *         operation for this Component
7309      * @since 1.4
7310      */
7311     public void setFocusTraversalKeys(int id,
7312                                       Set<? extends AWTKeyStroke> keystrokes)
7313     {
7314         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {
7315             throw new IllegalArgumentException("invalid focus traversal key identifier");
7316         }
7317 
7318         setFocusTraversalKeys_NoIDCheck(id, keystrokes);
7319     }
7320 
7321     /**
7322      * Returns the Set of focus traversal keys for a given traversal operation
7323      * for this Component. (See
7324      * {@code setFocusTraversalKeys} for a full description of each key.)
7325      * <p>
7326      * If a Set of traversal keys has not been explicitly defined for this
7327      * Component, then this Component's parent's Set is returned. If no Set
7328      * has been explicitly defined for any of this Component's ancestors, then
7329      * the current KeyboardFocusManager's default Set is returned.
7330      *
7331      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7332      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7333      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7334      * @return the Set of AWTKeyStrokes for the specified operation. The Set
7335      *         will be unmodifiable, and may be empty. null will never be
7336      *         returned.
7337      * @see #setFocusTraversalKeys
7338      * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
7339      * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
7340      * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
7341      * @throws IllegalArgumentException if id is not one of
7342      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7343      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7344      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7345      * @since 1.4
7346      */
7347     public Set<AWTKeyStroke> getFocusTraversalKeys(int id) {
7348         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {
7349             throw new IllegalArgumentException("invalid focus traversal key identifier");
7350         }
7351 
7352         return getFocusTraversalKeys_NoIDCheck(id);
7353     }
7354 
7355     // We define these methods so that Container does not need to repeat this
7356     // code. Container cannot call super.<method> because Container allows
7357     // DOWN_CYCLE_TRAVERSAL_KEY while Component does not. The Component method
7358     // would erroneously generate an IllegalArgumentException for
7359     // DOWN_CYCLE_TRAVERSAL_KEY.
7360     final void setFocusTraversalKeys_NoIDCheck(int id, Set<? extends AWTKeyStroke> keystrokes) {
7361         Set<AWTKeyStroke> oldKeys;
7362 
7363         synchronized (this) {
7364             if (focusTraversalKeys == null) {
7365                 initializeFocusTraversalKeys();
7366             }
7367 
7368             if (keystrokes != null) {
7369                 for (AWTKeyStroke keystroke : keystrokes ) {
7370 
7371                     if (keystroke == null) {
7372                         throw new IllegalArgumentException("cannot set null focus traversal key");
7373                     }
7374 
7375                     if (keystroke.getKeyChar() != KeyEvent.CHAR_UNDEFINED) {
7376                         throw new IllegalArgumentException("focus traversal keys cannot map to KEY_TYPED events");
7377                     }
7378 
7379                     for (int i = 0; i < focusTraversalKeys.length; i++) {
7380                         if (i == id) {
7381                             continue;
7382                         }
7383 
7384                         if (getFocusTraversalKeys_NoIDCheck(i).contains(keystroke))
7385                         {
7386                             throw new IllegalArgumentException("focus traversal keys must be unique for a Component");
7387                         }
7388                     }
7389                 }
7390             }
7391 
7392             oldKeys = focusTraversalKeys[id];
7393             focusTraversalKeys[id] = (keystrokes != null)
7394                 ? Collections.unmodifiableSet(new HashSet<AWTKeyStroke>(keystrokes))
7395                 : null;
7396         }
7397 
7398         firePropertyChange(focusTraversalKeyPropertyNames[id], oldKeys,
7399                            keystrokes);
7400     }
7401     final Set<AWTKeyStroke> getFocusTraversalKeys_NoIDCheck(int id) {
7402         // Okay to return Set directly because it is an unmodifiable view
7403         @SuppressWarnings("unchecked")
7404         Set<AWTKeyStroke> keystrokes = (focusTraversalKeys != null)
7405             ? focusTraversalKeys[id]
7406             : null;
7407 
7408         if (keystrokes != null) {
7409             return keystrokes;
7410         } else {
7411             Container parent = this.parent;
7412             if (parent != null) {
7413                 return parent.getFocusTraversalKeys(id);
7414             } else {
7415                 return KeyboardFocusManager.getCurrentKeyboardFocusManager().
7416                     getDefaultFocusTraversalKeys(id);
7417             }
7418         }
7419     }
7420 
7421     /**
7422      * Returns whether the Set of focus traversal keys for the given focus
7423      * traversal operation has been explicitly defined for this Component. If
7424      * this method returns {@code false}, this Component is inheriting the
7425      * Set from an ancestor, or from the current KeyboardFocusManager.
7426      *
7427      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7428      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7429      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7430      * @return {@code true} if the Set of focus traversal keys for the
7431      *         given focus traversal operation has been explicitly defined for
7432      *         this Component; {@code false} otherwise.
7433      * @throws IllegalArgumentException if id is not one of
7434      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7435      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7436      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7437      * @since 1.4
7438      */
7439     public boolean areFocusTraversalKeysSet(int id) {
7440         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {
7441             throw new IllegalArgumentException("invalid focus traversal key identifier");
7442         }
7443 
7444         return (focusTraversalKeys != null && focusTraversalKeys[id] != null);
7445     }
7446 
7447     /**
7448      * Sets whether focus traversal keys are enabled for this Component.
7449      * Components for which focus traversal keys are disabled receive key
7450      * events for focus traversal keys. Components for which focus traversal
7451      * keys are enabled do not see these events; instead, the events are
7452      * automatically converted to traversal operations.
7453      *
7454      * @param focusTraversalKeysEnabled whether focus traversal keys are
7455      *        enabled for this Component
7456      * @see #getFocusTraversalKeysEnabled
7457      * @see #setFocusTraversalKeys
7458      * @see #getFocusTraversalKeys
7459      * @since 1.4
7460      */
7461     public void setFocusTraversalKeysEnabled(boolean
7462                                              focusTraversalKeysEnabled) {
7463         boolean oldFocusTraversalKeysEnabled;
7464         synchronized (this) {
7465             oldFocusTraversalKeysEnabled = this.focusTraversalKeysEnabled;
7466             this.focusTraversalKeysEnabled = focusTraversalKeysEnabled;
7467         }
7468         firePropertyChange("focusTraversalKeysEnabled",
7469                            oldFocusTraversalKeysEnabled,
7470                            focusTraversalKeysEnabled);
7471     }
7472 
7473     /**
7474      * Returns whether focus traversal keys are enabled for this Component.
7475      * Components for which focus traversal keys are disabled receive key
7476      * events for focus traversal keys. Components for which focus traversal
7477      * keys are enabled do not see these events; instead, the events are
7478      * automatically converted to traversal operations.
7479      *
7480      * @return whether focus traversal keys are enabled for this Component
7481      * @see #setFocusTraversalKeysEnabled
7482      * @see #setFocusTraversalKeys
7483      * @see #getFocusTraversalKeys
7484      * @since 1.4
7485      */
7486     public boolean getFocusTraversalKeysEnabled() {
7487         return focusTraversalKeysEnabled;
7488     }
7489 
7490     /**
7491      * Requests that this Component get the input focus, and that this
7492      * Component's top-level ancestor become the focused Window. This
7493      * component must be displayable, focusable, visible and all of
7494      * its ancestors (with the exception of the top-level Window) must
7495      * be visible for the request to be granted. Every effort will be
7496      * made to honor the request; however, in some cases it may be
7497      * impossible to do so. Developers must never assume that this
7498      * Component is the focus owner until this Component receives a
7499      * FOCUS_GAINED event. If this request is denied because this
7500      * Component's top-level Window cannot become the focused Window,
7501      * the request will be remembered and will be granted when the
7502      * Window is later focused by the user.
7503      * <p>
7504      * This method cannot be used to set the focus owner to no Component at
7505      * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner()}
7506      * instead.
7507      * <p>
7508      * Because the focus behavior of this method is platform-dependent,
7509      * developers are strongly encouraged to use
7510      * {@code requestFocusInWindow} when possible.
7511      *
7512      * <p>Note: Not all focus transfers result from invoking this method. As
7513      * such, a component may receive focus without this or any of the other
7514      * {@code requestFocus} methods of {@code Component} being invoked.
7515      *
7516      * @see #requestFocusInWindow
7517      * @see java.awt.event.FocusEvent
7518      * @see #addFocusListener
7519      * @see #isFocusable
7520      * @see #isDisplayable
7521      * @see KeyboardFocusManager#clearGlobalFocusOwner
7522      * @since 1.0
7523      */
7524     public void requestFocus() {
7525         requestFocusHelper(false, true);
7526     }
7527 
7528 
7529     /**
7530      * Requests by the reason of {@code cause} that this Component get the input
7531      * focus, and that this Component's top-level ancestor become the
7532      * focused Window. This component must be displayable, focusable, visible
7533      * and all of its ancestors (with the exception of the top-level Window)
7534      * must be visible for the request to be granted. Every effort will be
7535      * made to honor the request; however, in some cases it may be
7536      * impossible to do so. Developers must never assume that this
7537      * Component is the focus owner until this Component receives a
7538      * FOCUS_GAINED event.
7539      * <p>
7540      * The focus request effect may also depend on the provided
7541      * cause value. If this request is succeed the {@code FocusEvent}
7542      * generated in the result will receive the cause value specified as the
7543      * argument of method. If this request is denied because this Component's
7544      * top-level Window cannot become the focused Window, the request will be
7545      * remembered and will be granted when the Window is later focused by the
7546      * user.
7547      * <p>
7548      * This method cannot be used to set the focus owner to no Component at
7549      * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner()}
7550      * instead.
7551      * <p>
7552      * Because the focus behavior of this method is platform-dependent,
7553      * developers are strongly encouraged to use
7554      * {@code requestFocusInWindow(FocusEvent.Cause)} when possible.
7555      *
7556      * <p>Note: Not all focus transfers result from invoking this method. As
7557      * such, a component may receive focus without this or any of the other
7558      * {@code requestFocus} methods of {@code Component} being invoked.
7559      *
7560      * @param  cause the cause why the focus is requested
7561      * @see FocusEvent
7562      * @see FocusEvent.Cause
7563      * @see #requestFocusInWindow(FocusEvent.Cause)
7564      * @see java.awt.event.FocusEvent
7565      * @see #addFocusListener
7566      * @see #isFocusable
7567      * @see #isDisplayable
7568      * @see KeyboardFocusManager#clearGlobalFocusOwner
7569      * @since 9
7570      */
7571     public void requestFocus(FocusEvent.Cause cause) {
7572         requestFocusHelper(false, true, cause);
7573     }
7574 
7575     /**
7576      * Requests that this {@code Component} get the input focus,
7577      * and that this {@code Component}'s top-level ancestor
7578      * become the focused {@code Window}. This component must be
7579      * displayable, focusable, visible and all of its ancestors (with
7580      * the exception of the top-level Window) must be visible for the
7581      * request to be granted. Every effort will be made to honor the
7582      * request; however, in some cases it may be impossible to do
7583      * so. Developers must never assume that this component is the
7584      * focus owner until this component receives a FOCUS_GAINED
7585      * event. If this request is denied because this component's
7586      * top-level window cannot become the focused window, the request
7587      * will be remembered and will be granted when the window is later
7588      * focused by the user.
7589      * <p>
7590      * This method returns a boolean value. If {@code false} is returned,
7591      * the request is <b>guaranteed to fail</b>. If {@code true} is
7592      * returned, the request will succeed <b>unless</b> it is vetoed, or an
7593      * extraordinary event, such as disposal of the component's peer, occurs
7594      * before the request can be granted by the native windowing system. Again,
7595      * while a return value of {@code true} indicates that the request is
7596      * likely to succeed, developers must never assume that this component is
7597      * the focus owner until this component receives a FOCUS_GAINED event.
7598      * <p>
7599      * This method cannot be used to set the focus owner to no component at
7600      * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner}
7601      * instead.
7602      * <p>
7603      * Because the focus behavior of this method is platform-dependent,
7604      * developers are strongly encouraged to use
7605      * {@code requestFocusInWindow} when possible.
7606      * <p>
7607      * Every effort will be made to ensure that {@code FocusEvent}s
7608      * generated as a
7609      * result of this request will have the specified temporary value. However,
7610      * because specifying an arbitrary temporary state may not be implementable
7611      * on all native windowing systems, correct behavior for this method can be
7612      * guaranteed only for lightweight {@code Component}s.
7613      * This method is not intended
7614      * for general use, but exists instead as a hook for lightweight component
7615      * libraries, such as Swing.
7616      *
7617      * <p>Note: Not all focus transfers result from invoking this method. As
7618      * such, a component may receive focus without this or any of the other
7619      * {@code requestFocus} methods of {@code Component} being invoked.
7620      *
7621      * @param temporary true if the focus change is temporary,
7622      *        such as when the window loses the focus; for
7623      *        more information on temporary focus changes see the
7624      *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
7625      * @return {@code false} if the focus change request is guaranteed to
7626      *         fail; {@code true} if it is likely to succeed
7627      * @see java.awt.event.FocusEvent
7628      * @see #addFocusListener
7629      * @see #isFocusable
7630      * @see #isDisplayable
7631      * @see KeyboardFocusManager#clearGlobalFocusOwner
7632      * @since 1.4
7633      */
7634     protected boolean requestFocus(boolean temporary) {
7635         return requestFocusHelper(temporary, true);
7636     }
7637 
7638     /**
7639      * Requests by the reason of {@code cause} that this {@code Component} get
7640      * the input focus, and that this {@code Component}'s top-level ancestor
7641      * become the focused {@code Window}. This component must be
7642      * displayable, focusable, visible and all of its ancestors (with
7643      * the exception of the top-level Window) must be visible for the
7644      * request to be granted. Every effort will be made to honor the
7645      * request; however, in some cases it may be impossible to do
7646      * so. Developers must never assume that this component is the
7647      * focus owner until this component receives a FOCUS_GAINED
7648      * event. If this request is denied because this component's
7649      * top-level window cannot become the focused window, the request
7650      * will be remembered and will be granted when the window is later
7651      * focused by the user.
7652      * <p>
7653      * This method returns a boolean value. If {@code false} is returned,
7654      * the request is <b>guaranteed to fail</b>. If {@code true} is
7655      * returned, the request will succeed <b>unless</b> it is vetoed, or an
7656      * extraordinary event, such as disposal of the component's peer, occurs
7657      * before the request can be granted by the native windowing system. Again,
7658      * while a return value of {@code true} indicates that the request is
7659      * likely to succeed, developers must never assume that this component is
7660      * the focus owner until this component receives a FOCUS_GAINED event.
7661      * <p>
7662      * The focus request effect may also depend on the provided
7663      * cause value. If this request is succeed the {FocusEvent}
7664      * generated in the result will receive the cause value specified as the
7665      * argument of the method.
7666      * <p>
7667      * This method cannot be used to set the focus owner to no component at
7668      * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner}
7669      * instead.
7670      * <p>
7671      * Because the focus behavior of this method is platform-dependent,
7672      * developers are strongly encouraged to use
7673      * {@code requestFocusInWindow} when possible.
7674      * <p>
7675      * Every effort will be made to ensure that {@code FocusEvent}s
7676      * generated as a
7677      * result of this request will have the specified temporary value. However,
7678      * because specifying an arbitrary temporary state may not be implementable
7679      * on all native windowing systems, correct behavior for this method can be
7680      * guaranteed only for lightweight {@code Component}s.
7681      * This method is not intended
7682      * for general use, but exists instead as a hook for lightweight component
7683      * libraries, such as Swing.
7684      * <p>
7685      * Note: Not all focus transfers result from invoking this method. As
7686      * such, a component may receive focus without this or any of the other
7687      * {@code requestFocus} methods of {@code Component} being invoked.
7688      *
7689      * @param temporary true if the focus change is temporary,
7690      *        such as when the window loses the focus; for
7691      *        more information on temporary focus changes see the
7692      *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
7693      *
7694      * @param  cause the cause why the focus is requested
7695      * @return {@code false} if the focus change request is guaranteed to
7696      *         fail; {@code true} if it is likely to succeed
7697      * @see FocusEvent
7698      * @see FocusEvent.Cause
7699      * @see #addFocusListener
7700      * @see #isFocusable
7701      * @see #isDisplayable
7702      * @see KeyboardFocusManager#clearGlobalFocusOwner
7703      * @since 9
7704      */
7705     protected boolean requestFocus(boolean temporary, FocusEvent.Cause cause) {
7706         return requestFocusHelper(temporary, true, cause);
7707     }
7708 
7709     /**
7710      * Requests that this Component get the input focus, if this
7711      * Component's top-level ancestor is already the focused
7712      * Window. This component must be displayable, focusable, visible
7713      * and all of its ancestors (with the exception of the top-level
7714      * Window) must be visible for the request to be granted. Every
7715      * effort will be made to honor the request; however, in some
7716      * cases it may be impossible to do so. Developers must never
7717      * assume that this Component is the focus owner until this
7718      * Component receives a FOCUS_GAINED event.
7719      * <p>
7720      * This method returns a boolean value. If {@code false} is returned,
7721      * the request is <b>guaranteed to fail</b>. If {@code true} is
7722      * returned, the request will succeed <b>unless</b> it is vetoed, or an
7723      * extraordinary event, such as disposal of the Component's peer, occurs
7724      * before the request can be granted by the native windowing system. Again,
7725      * while a return value of {@code true} indicates that the request is
7726      * likely to succeed, developers must never assume that this Component is
7727      * the focus owner until this Component receives a FOCUS_GAINED event.
7728      * <p>
7729      * This method cannot be used to set the focus owner to no Component at
7730      * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner()}
7731      * instead.
7732      * <p>
7733      * The focus behavior of this method can be implemented uniformly across
7734      * platforms, and thus developers are strongly encouraged to use this
7735      * method over {@code requestFocus} when possible. Code which relies
7736      * on {@code requestFocus} may exhibit different focus behavior on
7737      * different platforms.
7738      *
7739      * <p>Note: Not all focus transfers result from invoking this method. As
7740      * such, a component may receive focus without this or any of the other
7741      * {@code requestFocus} methods of {@code Component} being invoked.
7742      *
7743      * @return {@code false} if the focus change request is guaranteed to
7744      *         fail; {@code true} if it is likely to succeed
7745      * @see #requestFocus
7746      * @see java.awt.event.FocusEvent
7747      * @see #addFocusListener
7748      * @see #isFocusable
7749      * @see #isDisplayable
7750      * @see KeyboardFocusManager#clearGlobalFocusOwner
7751      * @since 1.4
7752      */
7753     public boolean requestFocusInWindow() {
7754         return requestFocusHelper(false, false);
7755     }
7756 
7757     /**
7758      * Requests by the reason of {@code cause} that this Component get the input
7759      * focus, if this Component's top-level ancestor is already the focused
7760      * Window. This component must be displayable, focusable, visible
7761      * and all of its ancestors (with the exception of the top-level
7762      * Window) must be visible for the request to be granted. Every
7763      * effort will be made to honor the request; however, in some
7764      * cases it may be impossible to do so. Developers must never
7765      * assume that this Component is the focus owner until this
7766      * Component receives a FOCUS_GAINED event.
7767      * <p>
7768      * This method returns a boolean value. If {@code false} is returned,
7769      * the request is <b>guaranteed to fail</b>. If {@code true} is
7770      * returned, the request will succeed <b>unless</b> it is vetoed, or an
7771      * extraordinary event, such as disposal of the Component's peer, occurs
7772      * before the request can be granted by the native windowing system. Again,
7773      * while a return value of {@code true} indicates that the request is
7774      * likely to succeed, developers must never assume that this Component is
7775      * the focus owner until this Component receives a FOCUS_GAINED event.
7776      * <p>
7777      * The focus request effect may also depend on the provided
7778      * cause value. If this request is succeed the {@code FocusEvent}
7779      * generated in the result will receive the cause value specified as the
7780      * argument of the method.
7781      * <p>
7782      * This method cannot be used to set the focus owner to no Component at
7783      * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner()}
7784      * instead.
7785      * <p>
7786      * The focus behavior of this method can be implemented uniformly across
7787      * platforms, and thus developers are strongly encouraged to use this
7788      * method over {@code requestFocus(FocusEvent.Cause)} when possible.
7789      * Code which relies on {@code requestFocus(FocusEvent.Cause)} may exhibit
7790      * different focus behavior on different platforms.
7791      *
7792      * <p>Note: Not all focus transfers result from invoking this method. As
7793      * such, a component may receive focus without this or any of the other
7794      * {@code requestFocus} methods of {@code Component} being invoked.
7795      *
7796      * @param  cause the cause why the focus is requested
7797      * @return {@code false} if the focus change request is guaranteed to
7798      *         fail; {@code true} if it is likely to succeed
7799      * @see #requestFocus(FocusEvent.Cause)
7800      * @see FocusEvent
7801      * @see FocusEvent.Cause
7802      * @see java.awt.event.FocusEvent
7803      * @see #addFocusListener
7804      * @see #isFocusable
7805      * @see #isDisplayable
7806      * @see KeyboardFocusManager#clearGlobalFocusOwner
7807      * @since 9
7808      */
7809     public boolean requestFocusInWindow(FocusEvent.Cause cause) {
7810         return requestFocusHelper(false, false, cause);
7811     }
7812 
7813     /**
7814      * Requests that this {@code Component} get the input focus,
7815      * if this {@code Component}'s top-level ancestor is already
7816      * the focused {@code Window}.  This component must be
7817      * displayable, focusable, visible and all of its ancestors (with
7818      * the exception of the top-level Window) must be visible for the
7819      * request to be granted. Every effort will be made to honor the
7820      * request; however, in some cases it may be impossible to do
7821      * so. Developers must never assume that this component is the
7822      * focus owner until this component receives a FOCUS_GAINED event.
7823      * <p>
7824      * This method returns a boolean value. If {@code false} is returned,
7825      * the request is <b>guaranteed to fail</b>. If {@code true} is
7826      * returned, the request will succeed <b>unless</b> it is vetoed, or an
7827      * extraordinary event, such as disposal of the component's peer, occurs
7828      * before the request can be granted by the native windowing system. Again,
7829      * while a return value of {@code true} indicates that the request is
7830      * likely to succeed, developers must never assume that this component is
7831      * the focus owner until this component receives a FOCUS_GAINED event.
7832      * <p>
7833      * This method cannot be used to set the focus owner to no component at
7834      * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner}
7835      * instead.
7836      * <p>
7837      * The focus behavior of this method can be implemented uniformly across
7838      * platforms, and thus developers are strongly encouraged to use this
7839      * method over {@code requestFocus} when possible. Code which relies
7840      * on {@code requestFocus} may exhibit different focus behavior on
7841      * different platforms.
7842      * <p>
7843      * Every effort will be made to ensure that {@code FocusEvent}s
7844      * generated as a
7845      * result of this request will have the specified temporary value. However,
7846      * because specifying an arbitrary temporary state may not be implementable
7847      * on all native windowing systems, correct behavior for this method can be
7848      * guaranteed only for lightweight components. This method is not intended
7849      * for general use, but exists instead as a hook for lightweight component
7850      * libraries, such as Swing.
7851      *
7852      * <p>Note: Not all focus transfers result from invoking this method. As
7853      * such, a component may receive focus without this or any of the other
7854      * {@code requestFocus} methods of {@code Component} being invoked.
7855      *
7856      * @param temporary true if the focus change is temporary,
7857      *        such as when the window loses the focus; for
7858      *        more information on temporary focus changes see the
7859      *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
7860      * @return {@code false} if the focus change request is guaranteed to
7861      *         fail; {@code true} if it is likely to succeed
7862      * @see #requestFocus
7863      * @see java.awt.event.FocusEvent
7864      * @see #addFocusListener
7865      * @see #isFocusable
7866      * @see #isDisplayable
7867      * @see KeyboardFocusManager#clearGlobalFocusOwner
7868      * @since 1.4
7869      */
7870     protected boolean requestFocusInWindow(boolean temporary) {
7871         return requestFocusHelper(temporary, false);
7872     }
7873 
7874     boolean requestFocusInWindow(boolean temporary, FocusEvent.Cause cause) {
7875         return requestFocusHelper(temporary, false, cause);
7876     }
7877 
7878     final boolean requestFocusHelper(boolean temporary,
7879                                      boolean focusedWindowChangeAllowed) {
7880         return requestFocusHelper(temporary, focusedWindowChangeAllowed, FocusEvent.Cause.UNKNOWN);
7881     }
7882 
7883     final boolean requestFocusHelper(boolean temporary,
7884                                      boolean focusedWindowChangeAllowed,
7885                                      FocusEvent.Cause cause)
7886     {
7887         // 1) Check if the event being dispatched is a system-generated mouse event.
7888         AWTEvent currentEvent = EventQueue.getCurrentEvent();
7889         if (currentEvent instanceof MouseEvent &&
7890             SunToolkit.isSystemGenerated(currentEvent))
7891         {
7892             // 2) Sanity check: if the mouse event component source belongs to the same containing window.
7893             Component source = ((MouseEvent)currentEvent).getComponent();
7894             if (source == null || source.getContainingWindow() == getContainingWindow()) {
7895                 focusLog.finest("requesting focus by mouse event \"in window\"");
7896 
7897                 // If both the conditions are fulfilled the focus request should be strictly
7898                 // bounded by the toplevel window. It's assumed that the mouse event activates
7899                 // the window (if it wasn't active) and this makes it possible for a focus
7900                 // request with a strong in-window requirement to change focus in the bounds
7901                 // of the toplevel. If, by any means, due to asynchronous nature of the event
7902                 // dispatching mechanism, the window happens to be natively inactive by the time
7903                 // this focus request is eventually handled, it should not re-activate the
7904                 // toplevel. Otherwise the result may not meet user expectations. See 6981400.
7905                 focusedWindowChangeAllowed = false;
7906             }
7907         }
7908         if (!isRequestFocusAccepted(temporary, focusedWindowChangeAllowed, cause)) {
7909             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7910                 focusLog.finest("requestFocus is not accepted");
7911             }
7912             return false;
7913         }
7914         // Update most-recent map
7915         KeyboardFocusManager.setMostRecentFocusOwner(this);
7916 
7917         Component window = this;
7918         while ( (window != null) && !(window instanceof Window)) {
7919             if (!window.isVisible()) {
7920                 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7921                     focusLog.finest("component is recursively invisible");
7922                 }
7923                 return false;
7924             }
7925             window = window.parent;
7926         }
7927 
7928         ComponentPeer peer = this.peer;
7929         Component heavyweight = (peer instanceof LightweightPeer)
7930             ? getNativeContainer() : this;
7931         if (heavyweight == null || !heavyweight.isVisible()) {
7932             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7933                 focusLog.finest("Component is not a part of visible hierarchy");
7934             }
7935             return false;
7936         }
7937         peer = heavyweight.peer;
7938         if (peer == null) {
7939             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7940                 focusLog.finest("Peer is null");
7941             }
7942             return false;
7943         }
7944 
7945         // Focus this Component
7946         long time = 0;
7947         if (EventQueue.isDispatchThread()) {
7948             time = Toolkit.getEventQueue().getMostRecentKeyEventTime();
7949         } else {
7950             // A focus request made from outside EDT should not be associated with any event
7951             // and so its time stamp is simply set to the current time.
7952             time = System.currentTimeMillis();
7953         }
7954 
7955         boolean success = peer.requestFocus
7956             (this, temporary, focusedWindowChangeAllowed, time, cause);
7957         if (!success) {
7958             KeyboardFocusManager.getCurrentKeyboardFocusManager
7959                 (appContext).dequeueKeyEvents(time, this);
7960             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7961                 focusLog.finest("Peer request failed");
7962             }
7963         } else {
7964             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7965                 focusLog.finest("Pass for " + this);
7966             }
7967         }
7968         return success;
7969     }
7970 
7971     private boolean isRequestFocusAccepted(boolean temporary,
7972                                            boolean focusedWindowChangeAllowed,
7973                                            FocusEvent.Cause cause)
7974     {
7975         if (!isFocusable() || !isVisible()) {
7976             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7977                 focusLog.finest("Not focusable or not visible");
7978             }
7979             return false;
7980         }
7981 
7982         ComponentPeer peer = this.peer;
7983         if (peer == null) {
7984             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7985                 focusLog.finest("peer is null");
7986             }
7987             return false;
7988         }
7989 
7990         Window window = getContainingWindow();
7991         if (window == null || !window.isFocusableWindow()) {
7992             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7993                 focusLog.finest("Component doesn't have toplevel");
7994             }
7995             return false;
7996         }
7997 
7998         // We have passed all regular checks for focus request,
7999         // now let's call RequestFocusController and see what it says.
8000         Component focusOwner = KeyboardFocusManager.getMostRecentFocusOwner(window);
8001         if (focusOwner == null) {
8002             // sometimes most recent focus owner may be null, but focus owner is not
8003             // e.g. we reset most recent focus owner if user removes focus owner
8004             focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
8005             if (focusOwner != null && focusOwner.getContainingWindow() != window) {
8006                 focusOwner = null;
8007             }
8008         }
8009 
8010         if (focusOwner == this || focusOwner == null) {
8011             // Controller is supposed to verify focus transfers and for this it
8012             // should know both from and to components.  And it shouldn't verify
8013             // transfers from when these components are equal.
8014             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
8015                 focusLog.finest("focus owner is null or this");
8016             }
8017             return true;
8018         }
8019 
8020         if (FocusEvent.Cause.ACTIVATION == cause) {
8021             // we shouldn't call RequestFocusController in case we are
8022             // in activation.  We do request focus on component which
8023             // has got temporary focus lost and then on component which is
8024             // most recent focus owner.  But most recent focus owner can be
8025             // changed by requestFocusXXX() call only, so this transfer has
8026             // been already approved.
8027             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
8028                 focusLog.finest("cause is activation");
8029             }
8030             return true;
8031         }
8032 
8033         boolean ret = Component.requestFocusController.acceptRequestFocus(focusOwner,
8034                                                                           this,
8035                                                                           temporary,
8036                                                                           focusedWindowChangeAllowed,
8037                                                                           cause);
8038         if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
8039             focusLog.finest("RequestFocusController returns {0}", ret);
8040         }
8041 
8042         return ret;
8043     }
8044 
8045     private static RequestFocusController requestFocusController = new DummyRequestFocusController();
8046 
8047     // Swing access this method through reflection to implement InputVerifier's functionality.
8048     // Perhaps, we should make this method public (later ;)
8049     private static class DummyRequestFocusController implements RequestFocusController {
8050         public boolean acceptRequestFocus(Component from, Component to,
8051                                           boolean temporary, boolean focusedWindowChangeAllowed,
8052                                           FocusEvent.Cause cause)
8053         {
8054             return true;
8055         }
8056     };
8057 
8058     static synchronized void setRequestFocusController(RequestFocusController requestController)
8059     {
8060         if (requestController == null) {
8061             requestFocusController = new DummyRequestFocusController();
8062         } else {
8063             requestFocusController = requestController;
8064         }
8065     }
8066 
8067     /**
8068      * Returns the Container which is the focus cycle root of this Component's
8069      * focus traversal cycle. Each focus traversal cycle has only a single
8070      * focus cycle root and each Component which is not a Container belongs to
8071      * only a single focus traversal cycle. Containers which are focus cycle
8072      * roots belong to two cycles: one rooted at the Container itself, and one
8073      * rooted at the Container's nearest focus-cycle-root ancestor. For such
8074      * Containers, this method will return the Container's nearest focus-cycle-
8075      * root ancestor.
8076      *
8077      * @return this Component's nearest focus-cycle-root ancestor
8078      * @see Container#isFocusCycleRoot()
8079      * @since 1.4
8080      */
8081     public Container getFocusCycleRootAncestor() {
8082         Container rootAncestor = this.parent;
8083         while (rootAncestor != null && !rootAncestor.isFocusCycleRoot()) {
8084             rootAncestor = rootAncestor.parent;
8085         }
8086         return rootAncestor;
8087     }
8088 
8089     /**
8090      * Returns whether the specified Container is the focus cycle root of this
8091      * Component's focus traversal cycle. Each focus traversal cycle has only
8092      * a single focus cycle root and each Component which is not a Container
8093      * belongs to only a single focus traversal cycle.
8094      *
8095      * @param container the Container to be tested
8096      * @return {@code true} if the specified Container is a focus-cycle-
8097      *         root of this Component; {@code false} otherwise
8098      * @see Container#isFocusCycleRoot()
8099      * @since 1.4
8100      */
8101     public boolean isFocusCycleRoot(Container container) {
8102         Container rootAncestor = getFocusCycleRootAncestor();
8103         return (rootAncestor == container);
8104     }
8105 
8106     Container getTraversalRoot() {
8107         return getFocusCycleRootAncestor();
8108     }
8109 
8110     /**
8111      * Transfers the focus to the next component, as though this Component were
8112      * the focus owner.
8113      * @see       #requestFocus()
8114      * @since     1.1
8115      */
8116     public void transferFocus() {
8117         nextFocus();
8118     }
8119 
8120     /**
8121      * @deprecated As of JDK version 1.1,
8122      * replaced by transferFocus().
8123      */
8124     @Deprecated
8125     public void nextFocus() {
8126         transferFocus(false);
8127     }
8128 
8129     boolean transferFocus(boolean clearOnFailure) {
8130         if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
8131             focusLog.finer("clearOnFailure = " + clearOnFailure);
8132         }
8133         Component toFocus = getNextFocusCandidate();
8134         boolean res = false;
8135         if (toFocus != null && !toFocus.isFocusOwner() && toFocus != this) {
8136             res = toFocus.requestFocusInWindow(FocusEvent.Cause.TRAVERSAL_FORWARD);
8137         }
8138         if (clearOnFailure && !res) {
8139             if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
8140                 focusLog.finer("clear global focus owner");
8141             }
8142             KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwnerPriv();
8143         }
8144         if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
8145             focusLog.finer("returning result: " + res);
8146         }
8147         return res;
8148     }
8149 
8150     @SuppressWarnings("deprecation")
8151     final Component getNextFocusCandidate() {
8152         Container rootAncestor = getTraversalRoot();
8153         Component comp = this;
8154         while (rootAncestor != null &&
8155                !(rootAncestor.isShowing() && rootAncestor.canBeFocusOwner()))
8156         {
8157             comp = rootAncestor;
8158             rootAncestor = comp.getFocusCycleRootAncestor();
8159         }
8160         if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
8161             focusLog.finer("comp = " + comp + ", root = " + rootAncestor);
8162         }
8163         Component candidate = null;
8164         if (rootAncestor != null) {
8165             FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy();
8166             Component toFocus = policy.getComponentAfter(rootAncestor, comp);
8167             if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
8168                 focusLog.finer("component after is " + toFocus);
8169             }
8170             if (toFocus == null) {
8171                 toFocus = policy.getDefaultComponent(rootAncestor);
8172                 if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
8173                     focusLog.finer("default component is " + toFocus);
8174                 }
8175             }
8176             if (toFocus == null) {
8177                 Applet applet = EmbeddedFrame.getAppletIfAncestorOf(this);
8178                 if (applet != null) {
8179                     toFocus = applet;
8180                 }
8181             }
8182             candidate = toFocus;
8183         }
8184         if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
8185             focusLog.finer("Focus transfer candidate: " + candidate);
8186         }
8187         return candidate;
8188     }
8189 
8190     /**
8191      * Transfers the focus to the previous component, as though this Component
8192      * were the focus owner.
8193      * @see       #requestFocus()
8194      * @since     1.4
8195      */
8196     public void transferFocusBackward() {
8197         transferFocusBackward(false);
8198     }
8199 
8200     boolean transferFocusBackward(boolean clearOnFailure) {
8201         Container rootAncestor = getTraversalRoot();
8202         Component comp = this;
8203         while (rootAncestor != null &&
8204                !(rootAncestor.isShowing() && rootAncestor.canBeFocusOwner()))
8205         {
8206             comp = rootAncestor;
8207             rootAncestor = comp.getFocusCycleRootAncestor();
8208         }
8209         boolean res = false;
8210         if (rootAncestor != null) {
8211             FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy();
8212             Component toFocus = policy.getComponentBefore(rootAncestor, comp);
8213             if (toFocus == null) {
8214                 toFocus = policy.getDefaultComponent(rootAncestor);
8215             }
8216             if (toFocus != null) {
8217                 res = toFocus.requestFocusInWindow(FocusEvent.Cause.TRAVERSAL_BACKWARD);
8218             }
8219         }
8220         if (clearOnFailure && !res) {
8221             if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
8222                 focusLog.finer("clear global focus owner");
8223             }
8224             KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwnerPriv();
8225         }
8226         if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
8227             focusLog.finer("returning result: " + res);
8228         }
8229         return res;
8230     }
8231 
8232     /**
8233      * Transfers the focus up one focus traversal cycle. Typically, the focus
8234      * owner is set to this Component's focus cycle root, and the current focus
8235      * cycle root is set to the new focus owner's focus cycle root. If,
8236      * however, this Component's focus cycle root is a Window, then the focus
8237      * owner is set to the focus cycle root's default Component to focus, and
8238      * the current focus cycle root is unchanged.
8239      *
8240      * @see       #requestFocus()
8241      * @see       Container#isFocusCycleRoot()
8242      * @see       Container#setFocusCycleRoot(boolean)
8243      * @since     1.4
8244      */
8245     public void transferFocusUpCycle() {
8246         Container rootAncestor;
8247         for (rootAncestor = getFocusCycleRootAncestor();
8248              rootAncestor != null && !(rootAncestor.isShowing() &&
8249                                        rootAncestor.isFocusable() &&
8250                                        rootAncestor.isEnabled());
8251              rootAncestor = rootAncestor.getFocusCycleRootAncestor()) {
8252         }
8253 
8254         if (rootAncestor != null) {
8255             Container rootAncestorRootAncestor =
8256                 rootAncestor.getFocusCycleRootAncestor();
8257             Container fcr = (rootAncestorRootAncestor != null) ?
8258                 rootAncestorRootAncestor : rootAncestor;
8259 
8260             KeyboardFocusManager.getCurrentKeyboardFocusManager().
8261                 setGlobalCurrentFocusCycleRootPriv(fcr);
8262             rootAncestor.requestFocus(FocusEvent.Cause.TRAVERSAL_UP);
8263         } else {
8264             Window window = getContainingWindow();
8265 
8266             if (window != null) {
8267                 Component toFocus = window.getFocusTraversalPolicy().
8268                     getDefaultComponent(window);
8269                 if (toFocus != null) {
8270                     KeyboardFocusManager.getCurrentKeyboardFocusManager().
8271                         setGlobalCurrentFocusCycleRootPriv(window);
8272                     toFocus.requestFocus(FocusEvent.Cause.TRAVERSAL_UP);
8273                 }
8274             }
8275         }
8276     }
8277 
8278     /**
8279      * Returns {@code true} if this {@code Component} is the
8280      * focus owner.  This method is obsolete, and has been replaced by
8281      * {@code isFocusOwner()}.
8282      *
8283      * @return {@code true} if this {@code Component} is the
8284      *         focus owner; {@code false} otherwise
8285      * @since 1.2
8286      */
8287     public boolean hasFocus() {
8288         return (KeyboardFocusManager.getCurrentKeyboardFocusManager().
8289                 getFocusOwner() == this);
8290     }
8291 
8292     /**
8293      * Returns {@code true} if this {@code Component} is the
8294      *    focus owner.
8295      *
8296      * @return {@code true} if this {@code Component} is the
8297      *     focus owner; {@code false} otherwise
8298      * @since 1.4
8299      */
8300     public boolean isFocusOwner() {
8301         return hasFocus();
8302     }
8303 
8304     /*
8305      * Used to disallow auto-focus-transfer on disposal of the focus owner
8306      * in the process of disposing its parent container.
8307      */
8308     private boolean autoFocusTransferOnDisposal = true;
8309 
8310     void setAutoFocusTransferOnDisposal(boolean value) {
8311         autoFocusTransferOnDisposal = value;
8312     }
8313 
8314     boolean isAutoFocusTransferOnDisposal() {
8315         return autoFocusTransferOnDisposal;
8316     }
8317 
8318     /**
8319      * Adds the specified popup menu to the component.
8320      * @param     popup the popup menu to be added to the component.
8321      * @see       #remove(MenuComponent)
8322      * @exception NullPointerException if {@code popup} is {@code null}
8323      * @since     1.1
8324      */
8325     public void add(PopupMenu popup) {
8326         synchronized (getTreeLock()) {
8327             if (popup.parent != null) {
8328                 popup.parent.remove(popup);
8329             }
8330             if (popups == null) {
8331                 popups = new Vector<PopupMenu>();
8332             }
8333             popups.addElement(popup);
8334             popup.parent = this;
8335 
8336             if (peer != null) {
8337                 if (popup.peer == null) {
8338                     popup.addNotify();
8339                 }
8340             }
8341         }
8342     }
8343 
8344     /**
8345      * Removes the specified popup menu from the component.
8346      * @param     popup the popup menu to be removed
8347      * @see       #add(PopupMenu)
8348      * @since     1.1
8349      */
8350     @SuppressWarnings("unchecked")
8351     public void remove(MenuComponent popup) {
8352         synchronized (getTreeLock()) {
8353             if (popups == null) {
8354                 return;
8355             }
8356             int index = popups.indexOf(popup);
8357             if (index >= 0) {
8358                 PopupMenu pmenu = (PopupMenu)popup;
8359                 if (pmenu.peer != null) {
8360                     pmenu.removeNotify();
8361                 }
8362                 pmenu.parent = null;
8363                 popups.removeElementAt(index);
8364                 if (popups.size() == 0) {
8365                     popups = null;
8366                 }
8367             }
8368         }
8369     }
8370 
8371     /**
8372      * Returns a string representing the state of this component. This
8373      * method is intended to be used only for debugging purposes, and the
8374      * content and format of the returned string may vary between
8375      * implementations. The returned string may be empty but may not be
8376      * {@code null}.
8377      *
8378      * @return  a string representation of this component's state
8379      * @since     1.0
8380      */
8381     protected String paramString() {
8382         final String thisName = Objects.toString(getName(), "");
8383         final String invalid = isValid() ? "" : ",invalid";
8384         final String hidden = visible ? "" : ",hidden";
8385         final String disabled = enabled ? "" : ",disabled";
8386         return thisName + ',' + x + ',' + y + ',' + width + 'x' + height
8387                 + invalid + hidden + disabled;
8388     }
8389 
8390     /**
8391      * Returns a string representation of this component and its values.
8392      * @return    a string representation of this component
8393      * @since     1.0
8394      */
8395     public String toString() {
8396         return getClass().getName() + '[' + paramString() + ']';
8397     }
8398 
8399     /**
8400      * Prints a listing of this component to the standard system output
8401      * stream {@code System.out}.
8402      * @see       java.lang.System#out
8403      * @since     1.0
8404      */
8405     public void list() {
8406         list(System.out, 0);
8407     }
8408 
8409     /**
8410      * Prints a listing of this component to the specified output
8411      * stream.
8412      * @param    out   a print stream
8413      * @throws   NullPointerException if {@code out} is {@code null}
8414      * @since    1.0
8415      */
8416     public void list(PrintStream out) {
8417         list(out, 0);
8418     }
8419 
8420     /**
8421      * Prints out a list, starting at the specified indentation, to the
8422      * specified print stream.
8423      * @param     out      a print stream
8424      * @param     indent   number of spaces to indent
8425      * @see       java.io.PrintStream#println(java.lang.Object)
8426      * @throws    NullPointerException if {@code out} is {@code null}
8427      * @since     1.0
8428      */
8429     public void list(PrintStream out, int indent) {
8430         for (int i = 0 ; i < indent ; i++) {
8431             out.print(" ");
8432         }
8433         out.println(this);
8434     }
8435 
8436     /**
8437      * Prints a listing to the specified print writer.
8438      * @param  out  the print writer to print to
8439      * @throws NullPointerException if {@code out} is {@code null}
8440      * @since 1.1
8441      */
8442     public void list(PrintWriter out) {
8443         list(out, 0);
8444     }
8445 
8446     /**
8447      * Prints out a list, starting at the specified indentation, to
8448      * the specified print writer.
8449      * @param out the print writer to print to
8450      * @param indent the number of spaces to indent
8451      * @throws NullPointerException if {@code out} is {@code null}
8452      * @see       java.io.PrintStream#println(java.lang.Object)
8453      * @since 1.1
8454      */
8455     public void list(PrintWriter out, int indent) {
8456         for (int i = 0 ; i < indent ; i++) {
8457             out.print(" ");
8458         }
8459         out.println(this);
8460     }
8461 
8462     /*
8463      * Fetches the native container somewhere higher up in the component
8464      * tree that contains this component.
8465      */
8466     final Container getNativeContainer() {
8467         Container p = getContainer();
8468         while (p != null && p.peer instanceof LightweightPeer) {
8469             p = p.getContainer();
8470         }
8471         return p;
8472     }
8473 
8474     /**
8475      * Adds a PropertyChangeListener to the listener list. The listener is
8476      * registered for all bound properties of this class, including the
8477      * following:
8478      * <ul>
8479      *    <li>this Component's font ("font")</li>
8480      *    <li>this Component's background color ("background")</li>
8481      *    <li>this Component's foreground color ("foreground")</li>
8482      *    <li>this Component's focusability ("focusable")</li>
8483      *    <li>this Component's focus traversal keys enabled state
8484      *        ("focusTraversalKeysEnabled")</li>
8485      *    <li>this Component's Set of FORWARD_TRAVERSAL_KEYS
8486      *        ("forwardFocusTraversalKeys")</li>
8487      *    <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS
8488      *        ("backwardFocusTraversalKeys")</li>
8489      *    <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS
8490      *        ("upCycleFocusTraversalKeys")</li>
8491      *    <li>this Component's preferred size ("preferredSize")</li>
8492      *    <li>this Component's minimum size ("minimumSize")</li>
8493      *    <li>this Component's maximum size ("maximumSize")</li>
8494      *    <li>this Component's name ("name")</li>
8495      * </ul>
8496      * Note that if this {@code Component} is inheriting a bound property, then no
8497      * event will be fired in response to a change in the inherited property.
8498      * <p>
8499      * If {@code listener} is {@code null},
8500      * no exception is thrown and no action is performed.
8501      *
8502      * @param    listener  the property change listener to be added
8503      *
8504      * @see #removePropertyChangeListener
8505      * @see #getPropertyChangeListeners
8506      * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8507      */
8508     public void addPropertyChangeListener(
8509                                                        PropertyChangeListener listener) {
8510         synchronized (getObjectLock()) {
8511             if (listener == null) {
8512                 return;
8513             }
8514             if (changeSupport == null) {
8515                 changeSupport = new PropertyChangeSupport(this);
8516             }
8517             changeSupport.addPropertyChangeListener(listener);
8518         }
8519     }
8520 
8521     /**
8522      * Removes a PropertyChangeListener from the listener list. This method
8523      * should be used to remove PropertyChangeListeners that were registered
8524      * for all bound properties of this class.
8525      * <p>
8526      * If listener is null, no exception is thrown and no action is performed.
8527      *
8528      * @param listener the PropertyChangeListener to be removed
8529      *
8530      * @see #addPropertyChangeListener
8531      * @see #getPropertyChangeListeners
8532      * @see #removePropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener)
8533      */
8534     public void removePropertyChangeListener(
8535                                                           PropertyChangeListener listener) {
8536         synchronized (getObjectLock()) {
8537             if (listener == null || changeSupport == null) {
8538                 return;
8539             }
8540             changeSupport.removePropertyChangeListener(listener);
8541         }
8542     }
8543 
8544     /**
8545      * Returns an array of all the property change listeners
8546      * registered on this component.
8547      *
8548      * @return all of this component's {@code PropertyChangeListener}s
8549      *         or an empty array if no property change
8550      *         listeners are currently registered
8551      *
8552      * @see      #addPropertyChangeListener
8553      * @see      #removePropertyChangeListener
8554      * @see      #getPropertyChangeListeners(java.lang.String)
8555      * @see      java.beans.PropertyChangeSupport#getPropertyChangeListeners
8556      * @since    1.4
8557      */
8558     public PropertyChangeListener[] getPropertyChangeListeners() {
8559         synchronized (getObjectLock()) {
8560             if (changeSupport == null) {
8561                 return new PropertyChangeListener[0];
8562             }
8563             return changeSupport.getPropertyChangeListeners();
8564         }
8565     }
8566 
8567     /**
8568      * Adds a PropertyChangeListener to the listener list for a specific
8569      * property. The specified property may be user-defined, or one of the
8570      * following:
8571      * <ul>
8572      *    <li>this Component's font ("font")</li>
8573      *    <li>this Component's background color ("background")</li>
8574      *    <li>this Component's foreground color ("foreground")</li>
8575      *    <li>this Component's focusability ("focusable")</li>
8576      *    <li>this Component's focus traversal keys enabled state
8577      *        ("focusTraversalKeysEnabled")</li>
8578      *    <li>this Component's Set of FORWARD_TRAVERSAL_KEYS
8579      *        ("forwardFocusTraversalKeys")</li>
8580      *    <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS
8581      *        ("backwardFocusTraversalKeys")</li>
8582      *    <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS
8583      *        ("upCycleFocusTraversalKeys")</li>
8584      * </ul>
8585      * Note that if this {@code Component} is inheriting a bound property, then no
8586      * event will be fired in response to a change in the inherited property.
8587      * <p>
8588      * If {@code propertyName} or {@code listener} is {@code null},
8589      * no exception is thrown and no action is taken.
8590      *
8591      * @param propertyName one of the property names listed above
8592      * @param listener the property change listener to be added
8593      *
8594      * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8595      * @see #getPropertyChangeListeners(java.lang.String)
8596      * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8597      */
8598     public void addPropertyChangeListener(
8599                                                        String propertyName,
8600                                                        PropertyChangeListener listener) {
8601         synchronized (getObjectLock()) {
8602             if (listener == null) {
8603                 return;
8604             }
8605             if (changeSupport == null) {
8606                 changeSupport = new PropertyChangeSupport(this);
8607             }
8608             changeSupport.addPropertyChangeListener(propertyName, listener);
8609         }
8610     }
8611 
8612     /**
8613      * Removes a {@code PropertyChangeListener} from the listener
8614      * list for a specific property. This method should be used to remove
8615      * {@code PropertyChangeListener}s
8616      * that were registered for a specific bound property.
8617      * <p>
8618      * If {@code propertyName} or {@code listener} is {@code null},
8619      * no exception is thrown and no action is taken.
8620      *
8621      * @param propertyName a valid property name
8622      * @param listener the PropertyChangeListener to be removed
8623      *
8624      * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8625      * @see #getPropertyChangeListeners(java.lang.String)
8626      * @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
8627      */
8628     public void removePropertyChangeListener(
8629                                                           String propertyName,
8630                                                           PropertyChangeListener listener) {
8631         synchronized (getObjectLock()) {
8632             if (listener == null || changeSupport == null) {
8633                 return;
8634             }
8635             changeSupport.removePropertyChangeListener(propertyName, listener);
8636         }
8637     }
8638 
8639     /**
8640      * Returns an array of all the listeners which have been associated
8641      * with the named property.
8642      *
8643      * @param  propertyName the property name
8644      * @return all of the {@code PropertyChangeListener}s associated with
8645      *         the named property; if no such listeners have been added or
8646      *         if {@code propertyName} is {@code null}, an empty
8647      *         array is returned
8648      *
8649      * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8650      * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8651      * @see #getPropertyChangeListeners
8652      * @since 1.4
8653      */
8654     public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) {
8655         synchronized (getObjectLock()) {
8656             if (changeSupport == null) {
8657                 return new PropertyChangeListener[0];
8658             }
8659             return changeSupport.getPropertyChangeListeners(propertyName);
8660         }
8661     }
8662 
8663     /**
8664      * Support for reporting bound property changes for Object properties.
8665      * This method can be called when a bound property has changed and it will
8666      * send the appropriate PropertyChangeEvent to any registered
8667      * PropertyChangeListeners.
8668      *
8669      * @param propertyName the property whose value has changed
8670      * @param oldValue the property's previous value
8671      * @param newValue the property's new value
8672      */
8673     protected void firePropertyChange(String propertyName,
8674                                       Object oldValue, Object newValue) {
8675         PropertyChangeSupport changeSupport;
8676         synchronized (getObjectLock()) {
8677             changeSupport = this.changeSupport;
8678         }
8679         if (changeSupport == null ||
8680             (oldValue != null && newValue != null && oldValue.equals(newValue))) {
8681             return;
8682         }
8683         changeSupport.firePropertyChange(propertyName, oldValue, newValue);
8684     }
8685 
8686     /**
8687      * Support for reporting bound property changes for boolean properties.
8688      * This method can be called when a bound property has changed and it will
8689      * send the appropriate PropertyChangeEvent to any registered
8690      * PropertyChangeListeners.
8691      *
8692      * @param propertyName the property whose value has changed
8693      * @param oldValue the property's previous value
8694      * @param newValue the property's new value
8695      * @since 1.4
8696      */
8697     protected void firePropertyChange(String propertyName,
8698                                       boolean oldValue, boolean newValue) {
8699         PropertyChangeSupport changeSupport = this.changeSupport;
8700         if (changeSupport == null || oldValue == newValue) {
8701             return;
8702         }
8703         changeSupport.firePropertyChange(propertyName, oldValue, newValue);
8704     }
8705 
8706     /**
8707      * Support for reporting bound property changes for integer properties.
8708      * This method can be called when a bound property has changed and it will
8709      * send the appropriate PropertyChangeEvent to any registered
8710      * PropertyChangeListeners.
8711      *
8712      * @param propertyName the property whose value has changed
8713      * @param oldValue the property's previous value
8714      * @param newValue the property's new value
8715      * @since 1.4
8716      */
8717     protected void firePropertyChange(String propertyName,
8718                                       int oldValue, int newValue) {
8719         PropertyChangeSupport changeSupport = this.changeSupport;
8720         if (changeSupport == null || oldValue == newValue) {
8721             return;
8722         }
8723         changeSupport.firePropertyChange(propertyName, oldValue, newValue);
8724     }
8725 
8726     /**
8727      * Reports a bound property change.
8728      *
8729      * @param propertyName the programmatic name of the property
8730      *          that was changed
8731      * @param oldValue the old value of the property (as a byte)
8732      * @param newValue the new value of the property (as a byte)
8733      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8734      *          java.lang.Object)
8735      * @since 1.5
8736      */
8737     public void firePropertyChange(String propertyName, byte oldValue, byte newValue) {
8738         if (changeSupport == null || oldValue == newValue) {
8739             return;
8740         }
8741         firePropertyChange(propertyName, Byte.valueOf(oldValue), Byte.valueOf(newValue));
8742     }
8743 
8744     /**
8745      * Reports a bound property change.
8746      *
8747      * @param propertyName the programmatic name of the property
8748      *          that was changed
8749      * @param oldValue the old value of the property (as a char)
8750      * @param newValue the new value of the property (as a char)
8751      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8752      *          java.lang.Object)
8753      * @since 1.5
8754      */
8755     public void firePropertyChange(String propertyName, char oldValue, char newValue) {
8756         if (changeSupport == null || oldValue == newValue) {
8757             return;
8758         }
8759         firePropertyChange(propertyName, Character.valueOf(oldValue), Character.valueOf(newValue));
8760     }
8761 
8762     /**
8763      * Reports a bound property change.
8764      *
8765      * @param propertyName the programmatic name of the property
8766      *          that was changed
8767      * @param oldValue the old value of the property (as a short)
8768      * @param newValue the new value of the property (as a short)
8769      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8770      *          java.lang.Object)
8771      * @since 1.5
8772      */
8773     public void firePropertyChange(String propertyName, short oldValue, short newValue) {
8774         if (changeSupport == null || oldValue == newValue) {
8775             return;
8776         }
8777         firePropertyChange(propertyName, Short.valueOf(oldValue), Short.valueOf(newValue));
8778     }
8779 
8780 
8781     /**
8782      * Reports a bound property change.
8783      *
8784      * @param propertyName the programmatic name of the property
8785      *          that was changed
8786      * @param oldValue the old value of the property (as a long)
8787      * @param newValue the new value of the property (as a long)
8788      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8789      *          java.lang.Object)
8790      * @since 1.5
8791      */
8792     public void firePropertyChange(String propertyName, long oldValue, long newValue) {
8793         if (changeSupport == null || oldValue == newValue) {
8794             return;
8795         }
8796         firePropertyChange(propertyName, Long.valueOf(oldValue), Long.valueOf(newValue));
8797     }
8798 
8799     /**
8800      * Reports a bound property change.
8801      *
8802      * @param propertyName the programmatic name of the property
8803      *          that was changed
8804      * @param oldValue the old value of the property (as a float)
8805      * @param newValue the new value of the property (as a float)
8806      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8807      *          java.lang.Object)
8808      * @since 1.5
8809      */
8810     public void firePropertyChange(String propertyName, float oldValue, float newValue) {
8811         if (changeSupport == null || oldValue == newValue) {
8812             return;
8813         }
8814         firePropertyChange(propertyName, Float.valueOf(oldValue), Float.valueOf(newValue));
8815     }
8816 
8817     /**
8818      * Reports a bound property change.
8819      *
8820      * @param propertyName the programmatic name of the property
8821      *          that was changed
8822      * @param oldValue the old value of the property (as a double)
8823      * @param newValue the new value of the property (as a double)
8824      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8825      *          java.lang.Object)
8826      * @since 1.5
8827      */
8828     public void firePropertyChange(String propertyName, double oldValue, double newValue) {
8829         if (changeSupport == null || oldValue == newValue) {
8830             return;
8831         }
8832         firePropertyChange(propertyName, Double.valueOf(oldValue), Double.valueOf(newValue));
8833     }
8834 
8835 
8836     // Serialization support.
8837 
8838     /**
8839      * Component Serialized Data Version.
8840      *
8841      * @serial
8842      */
8843     private int componentSerializedDataVersion = 4;
8844 
8845     /**
8846      * This hack is for Swing serialization. It will invoke
8847      * the Swing package private method {@code compWriteObjectNotify}.
8848      */
8849     private void doSwingSerialization() {
8850         if (!(this instanceof JComponent)) {
8851             return;
8852         }
8853         @SuppressWarnings("deprecation")
8854         Package swingPackage = Package.getPackage("javax.swing");
8855         // For Swing serialization to correctly work Swing needs to
8856         // be notified before Component does it's serialization.  This
8857         // hack accommodates this.
8858         //
8859         // Swing classes MUST be loaded by the bootstrap class loader,
8860         // otherwise we don't consider them.
8861         for (Class<?> klass = Component.this.getClass(); klass != null;
8862                    klass = klass.getSuperclass()) {
8863             if (klass.getPackage() == swingPackage &&
8864                       klass.getClassLoader() == null) {
8865 
8866                 SwingAccessor.getJComponentAccessor()
8867                         .compWriteObjectNotify((JComponent) this);
8868                 return;
8869             }
8870         }
8871     }
8872 
8873     /**
8874      * Writes default serializable fields to stream.  Writes
8875      * a variety of serializable listeners as optional data.
8876      * The non-serializable listeners are detected and
8877      * no attempt is made to serialize them.
8878      *
8879      * @param s the {@code ObjectOutputStream} to write
8880      * @serialData {@code null} terminated sequence of
8881      *   0 or more pairs; the pair consists of a {@code String}
8882      *   and an {@code Object}; the {@code String} indicates
8883      *   the type of object and is one of the following (as of 1.4):
8884      *   {@code componentListenerK} indicating an
8885      *     {@code ComponentListener} object;
8886      *   {@code focusListenerK} indicating an
8887      *     {@code FocusListener} object;
8888      *   {@code keyListenerK} indicating an
8889      *     {@code KeyListener} object;
8890      *   {@code mouseListenerK} indicating an
8891      *     {@code MouseListener} object;
8892      *   {@code mouseMotionListenerK} indicating an
8893      *     {@code MouseMotionListener} object;
8894      *   {@code inputMethodListenerK} indicating an
8895      *     {@code InputMethodListener} object;
8896      *   {@code hierarchyListenerK} indicating an
8897      *     {@code HierarchyListener} object;
8898      *   {@code hierarchyBoundsListenerK} indicating an
8899      *     {@code HierarchyBoundsListener} object;
8900      *   {@code mouseWheelListenerK} indicating an
8901      *     {@code MouseWheelListener} object
8902      * @serialData an optional {@code ComponentOrientation}
8903      *    (after {@code inputMethodListener}, as of 1.2)
8904      *
8905      * @see AWTEventMulticaster#save(java.io.ObjectOutputStream, java.lang.String, java.util.EventListener)
8906      * @see #componentListenerK
8907      * @see #focusListenerK
8908      * @see #keyListenerK
8909      * @see #mouseListenerK
8910      * @see #mouseMotionListenerK
8911      * @see #inputMethodListenerK
8912      * @see #hierarchyListenerK
8913      * @see #hierarchyBoundsListenerK
8914      * @see #mouseWheelListenerK
8915      * @see #readObject(ObjectInputStream)
8916      */
8917     private void writeObject(ObjectOutputStream s)
8918       throws IOException
8919     {
8920         doSwingSerialization();
8921 
8922         s.defaultWriteObject();
8923 
8924         AWTEventMulticaster.save(s, componentListenerK, componentListener);
8925         AWTEventMulticaster.save(s, focusListenerK, focusListener);
8926         AWTEventMulticaster.save(s, keyListenerK, keyListener);
8927         AWTEventMulticaster.save(s, mouseListenerK, mouseListener);
8928         AWTEventMulticaster.save(s, mouseMotionListenerK, mouseMotionListener);
8929         AWTEventMulticaster.save(s, inputMethodListenerK, inputMethodListener);
8930 
8931         s.writeObject(null);
8932         s.writeObject(componentOrientation);
8933 
8934         AWTEventMulticaster.save(s, hierarchyListenerK, hierarchyListener);
8935         AWTEventMulticaster.save(s, hierarchyBoundsListenerK,
8936                                  hierarchyBoundsListener);
8937         s.writeObject(null);
8938 
8939         AWTEventMulticaster.save(s, mouseWheelListenerK, mouseWheelListener);
8940         s.writeObject(null);
8941 
8942     }
8943 
8944     /**
8945      * Reads the {@code ObjectInputStream} and if it isn't
8946      * {@code null} adds a listener to receive a variety
8947      * of events fired by the component.
8948      * Unrecognized keys or values will be ignored.
8949      *
8950      * @param s the {@code ObjectInputStream} to read
8951      * @see #writeObject(ObjectOutputStream)
8952      */
8953     private void readObject(ObjectInputStream s)
8954       throws ClassNotFoundException, IOException
8955     {
8956         objectLock = new Object();
8957 
8958         acc = AccessController.getContext();
8959 
8960         s.defaultReadObject();
8961 
8962         appContext = AppContext.getAppContext();
8963         coalescingEnabled = checkCoalescing();
8964         if (componentSerializedDataVersion < 4) {
8965             // These fields are non-transient and rely on default
8966             // serialization. However, the default values are insufficient,
8967             // so we need to set them explicitly for object data streams prior
8968             // to 1.4.
8969             focusable = true;
8970             isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN;
8971             initializeFocusTraversalKeys();
8972             focusTraversalKeysEnabled = true;
8973         }
8974 
8975         Object keyOrNull;
8976         while(null != (keyOrNull = s.readObject())) {
8977             String key = ((String)keyOrNull).intern();
8978 
8979             if (componentListenerK == key)
8980                 addComponentListener((ComponentListener)(s.readObject()));
8981 
8982             else if (focusListenerK == key)
8983                 addFocusListener((FocusListener)(s.readObject()));
8984 
8985             else if (keyListenerK == key)
8986                 addKeyListener((KeyListener)(s.readObject()));
8987 
8988             else if (mouseListenerK == key)
8989                 addMouseListener((MouseListener)(s.readObject()));
8990 
8991             else if (mouseMotionListenerK == key)
8992                 addMouseMotionListener((MouseMotionListener)(s.readObject()));
8993 
8994             else if (inputMethodListenerK == key)
8995                 addInputMethodListener((InputMethodListener)(s.readObject()));
8996 
8997             else // skip value for unrecognized key
8998                 s.readObject();
8999 
9000         }
9001 
9002         // Read the component's orientation if it's present
9003         Object orient = null;
9004 
9005         try {
9006             orient = s.readObject();
9007         } catch (java.io.OptionalDataException e) {
9008             // JDK 1.1 instances will not have this optional data.
9009             // e.eof will be true to indicate that there is no more
9010             // data available for this object.
9011             // If e.eof is not true, throw the exception as it
9012             // might have been caused by reasons unrelated to
9013             // componentOrientation.
9014 
9015             if (!e.eof)  {
9016                 throw (e);
9017             }
9018         }
9019 
9020         if (orient != null) {
9021             componentOrientation = (ComponentOrientation)orient;
9022         } else {
9023             componentOrientation = ComponentOrientation.UNKNOWN;
9024         }
9025 
9026         try {
9027             while(null != (keyOrNull = s.readObject())) {
9028                 String key = ((String)keyOrNull).intern();
9029 
9030                 if (hierarchyListenerK == key) {
9031                     addHierarchyListener((HierarchyListener)(s.readObject()));
9032                 }
9033                 else if (hierarchyBoundsListenerK == key) {
9034                     addHierarchyBoundsListener((HierarchyBoundsListener)
9035                                                (s.readObject()));
9036                 }
9037                 else {
9038                     // skip value for unrecognized key
9039                     s.readObject();
9040                 }
9041             }
9042         } catch (java.io.OptionalDataException e) {
9043             // JDK 1.1/1.2 instances will not have this optional data.
9044             // e.eof will be true to indicate that there is no more
9045             // data available for this object.
9046             // If e.eof is not true, throw the exception as it
9047             // might have been caused by reasons unrelated to
9048             // hierarchy and hierarchyBounds listeners.
9049 
9050             if (!e.eof)  {
9051                 throw (e);
9052             }
9053         }
9054 
9055         try {
9056             while (null != (keyOrNull = s.readObject())) {
9057                 String key = ((String)keyOrNull).intern();
9058 
9059                 if (mouseWheelListenerK == key) {
9060                     addMouseWheelListener((MouseWheelListener)(s.readObject()));
9061                 }
9062                 else {
9063                     // skip value for unrecognized key
9064                     s.readObject();
9065                 }
9066             }
9067         } catch (java.io.OptionalDataException e) {
9068             // pre-1.3 instances will not have this optional data.
9069             // e.eof will be true to indicate that there is no more
9070             // data available for this object.
9071             // If e.eof is not true, throw the exception as it
9072             // might have been caused by reasons unrelated to
9073             // mouse wheel listeners
9074 
9075             if (!e.eof)  {
9076                 throw (e);
9077             }
9078         }
9079 
9080         if (popups != null) {
9081             int npopups = popups.size();
9082             for (int i = 0 ; i < npopups ; i++) {
9083                 PopupMenu popup = popups.elementAt(i);
9084                 popup.parent = this;
9085             }
9086         }
9087     }
9088 
9089     /**
9090      * Sets the language-sensitive orientation that is to be used to order
9091      * the elements or text within this component.  Language-sensitive
9092      * {@code LayoutManager} and {@code Component}
9093      * subclasses will use this property to
9094      * determine how to lay out and draw components.
9095      * <p>
9096      * At construction time, a component's orientation is set to
9097      * {@code ComponentOrientation.UNKNOWN},
9098      * indicating that it has not been specified
9099      * explicitly.  The UNKNOWN orientation behaves the same as
9100      * {@code ComponentOrientation.LEFT_TO_RIGHT}.
9101      * <p>
9102      * To set the orientation of a single component, use this method.
9103      * To set the orientation of an entire component
9104      * hierarchy, use
9105      * {@link #applyComponentOrientation applyComponentOrientation}.
9106      * <p>
9107      * This method changes layout-related information, and therefore,
9108      * invalidates the component hierarchy.
9109      *
9110      * @param  o the orientation to be set
9111      *
9112      * @see ComponentOrientation
9113      * @see #invalidate
9114      *
9115      * @author Laura Werner, IBM
9116      */
9117     public void setComponentOrientation(ComponentOrientation o) {
9118         ComponentOrientation oldValue = componentOrientation;
9119         componentOrientation = o;
9120 
9121         // This is a bound property, so report the change to
9122         // any registered listeners.  (Cheap if there are none.)
9123         firePropertyChange("componentOrientation", oldValue, o);
9124 
9125         // This could change the preferred size of the Component.
9126         invalidateIfValid();
9127     }
9128 
9129     /**
9130      * Retrieves the language-sensitive orientation that is to be used to order
9131      * the elements or text within this component.  {@code LayoutManager}
9132      * and {@code Component}
9133      * subclasses that wish to respect orientation should call this method to
9134      * get the component's orientation before performing layout or drawing.
9135      *
9136      * @return the orientation to order the elements or text
9137      * @see ComponentOrientation
9138      *
9139      * @author Laura Werner, IBM
9140      */
9141     public ComponentOrientation getComponentOrientation() {
9142         return componentOrientation;
9143     }
9144 
9145     /**
9146      * Sets the {@code ComponentOrientation} property of this component
9147      * and all components contained within it.
9148      * <p>
9149      * This method changes layout-related information, and therefore,
9150      * invalidates the component hierarchy.
9151      *
9152      *
9153      * @param orientation the new component orientation of this component and
9154      *        the components contained within it.
9155      * @exception NullPointerException if {@code orientation} is null.
9156      * @see #setComponentOrientation
9157      * @see #getComponentOrientation
9158      * @see #invalidate
9159      * @since 1.4
9160      */
9161     public void applyComponentOrientation(ComponentOrientation orientation) {
9162         if (orientation == null) {
9163             throw new NullPointerException();
9164         }
9165         setComponentOrientation(orientation);
9166     }
9167 
9168     final boolean canBeFocusOwner() {
9169         // It is enabled, visible, focusable.
9170         if (isEnabled() && isDisplayable() && isVisible() && isFocusable()) {
9171             return true;
9172         }
9173         return false;
9174     }
9175 
9176     /**
9177      * Checks that this component meets the prerequisites to be focus owner:
9178      * - it is enabled, visible, focusable
9179      * - it's parents are all enabled and showing
9180      * - top-level window is focusable
9181      * - if focus cycle root has DefaultFocusTraversalPolicy then it also checks that this policy accepts
9182      * this component as focus owner
9183      * @since 1.5
9184      */
9185     final boolean canBeFocusOwnerRecursively() {
9186         // - it is enabled, visible, focusable
9187         if (!canBeFocusOwner()) {
9188             return false;
9189         }
9190 
9191         // - it's parents are all enabled and showing
9192         synchronized(getTreeLock()) {
9193             if (parent != null) {
9194                 return parent.canContainFocusOwner(this);
9195             }
9196         }
9197         return true;
9198     }
9199 
9200     /**
9201      * Fix the location of the HW component in a LW container hierarchy.
9202      */
9203     final void relocateComponent() {
9204         synchronized (getTreeLock()) {
9205             if (peer == null) {
9206                 return;
9207             }
9208             int nativeX = x;
9209             int nativeY = y;
9210             for (Component cont = getContainer();
9211                     cont != null && cont.isLightweight();
9212                     cont = cont.getContainer())
9213             {
9214                 nativeX += cont.x;
9215                 nativeY += cont.y;
9216             }
9217             peer.setBounds(nativeX, nativeY, width, height,
9218                     ComponentPeer.SET_LOCATION);
9219         }
9220     }
9221 
9222     /**
9223      * Returns the {@code Window} ancestor of the component.
9224      * @return Window ancestor of the component or component by itself if it is Window;
9225      *         null, if component is not a part of window hierarchy
9226      */
9227     Window getContainingWindow() {
9228         return SunToolkit.getContainingWindow(this);
9229     }
9230 
9231     /**
9232      * Initialize JNI field and method IDs
9233      */
9234     private static native void initIDs();
9235 
9236     /*
9237      * --- Accessibility Support ---
9238      *
9239      *  Component will contain all of the methods in interface Accessible,
9240      *  though it won't actually implement the interface - that will be up
9241      *  to the individual objects which extend Component.
9242      */
9243 
9244     /**
9245      * The {@code AccessibleContext} associated with this {@code Component}.
9246      */
9247     protected AccessibleContext accessibleContext = null;
9248 
9249     /**
9250      * Gets the {@code AccessibleContext} associated
9251      * with this {@code Component}.
9252      * The method implemented by this base
9253      * class returns null.  Classes that extend {@code Component}
9254      * should implement this method to return the
9255      * {@code AccessibleContext} associated with the subclass.
9256      *
9257      *
9258      * @return the {@code AccessibleContext} of this
9259      *    {@code Component}
9260      * @since 1.3
9261      */
9262     public AccessibleContext getAccessibleContext() {
9263         return accessibleContext;
9264     }
9265 
9266     /**
9267      * Inner class of Component used to provide default support for
9268      * accessibility.  This class is not meant to be used directly by
9269      * application developers, but is instead meant only to be
9270      * subclassed by component developers.
9271      * <p>
9272      * The class used to obtain the accessible role for this object.
9273      * @since 1.3
9274      */
9275     protected abstract class AccessibleAWTComponent extends AccessibleContext
9276         implements Serializable, AccessibleComponent {
9277 
9278         private static final long serialVersionUID = 642321655757800191L;
9279 
9280         /**
9281          * Though the class is abstract, this should be called by
9282          * all sub-classes.
9283          */
9284         protected AccessibleAWTComponent() {
9285         }
9286 
9287         /**
9288          * Number of PropertyChangeListener objects registered. It's used
9289          * to add/remove ComponentListener and FocusListener to track
9290          * target Component's state.
9291          */
9292         private transient volatile int propertyListenersCount = 0;
9293 
9294         /**
9295          * A component listener to track show/hide/resize events
9296          * and convert them to PropertyChange events.
9297          */
9298         protected ComponentListener accessibleAWTComponentHandler = null;
9299 
9300         /**
9301          * A listener to track focus events
9302          * and convert them to PropertyChange events.
9303          */
9304         protected FocusListener accessibleAWTFocusHandler = null;
9305 
9306         /**
9307          * Fire PropertyChange listener, if one is registered,
9308          * when shown/hidden..
9309          * @since 1.3
9310          */
9311         protected class AccessibleAWTComponentHandler implements ComponentListener {
9312             public void componentHidden(ComponentEvent e)  {
9313                 if (accessibleContext != null) {
9314                     accessibleContext.firePropertyChange(
9315                                                          AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9316                                                          AccessibleState.VISIBLE, null);
9317                 }
9318             }
9319 
9320             public void componentShown(ComponentEvent e)  {
9321                 if (accessibleContext != null) {
9322                     accessibleContext.firePropertyChange(
9323                                                          AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9324                                                          null, AccessibleState.VISIBLE);
9325                 }
9326             }
9327 
9328             public void componentMoved(ComponentEvent e)  {
9329             }
9330 
9331             public void componentResized(ComponentEvent e)  {
9332             }
9333         } // inner class AccessibleAWTComponentHandler
9334 
9335 
9336         /**
9337          * Fire PropertyChange listener, if one is registered,
9338          * when focus events happen
9339          * @since 1.3
9340          */
9341         protected class AccessibleAWTFocusHandler implements FocusListener {
9342             public void focusGained(FocusEvent event) {
9343                 if (accessibleContext != null) {
9344                     accessibleContext.firePropertyChange(
9345                                                          AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9346                                                          null, AccessibleState.FOCUSED);
9347                 }
9348             }
9349             public void focusLost(FocusEvent event) {
9350                 if (accessibleContext != null) {
9351                     accessibleContext.firePropertyChange(
9352                                                          AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9353                                                          AccessibleState.FOCUSED, null);
9354                 }
9355             }
9356         }  // inner class AccessibleAWTFocusHandler
9357 
9358 
9359         /**
9360          * Adds a {@code PropertyChangeListener} to the listener list.
9361          *
9362          * @param listener  the property change listener to be added
9363          */
9364         public void addPropertyChangeListener(PropertyChangeListener listener) {
9365             if (accessibleAWTComponentHandler == null) {
9366                 accessibleAWTComponentHandler = new AccessibleAWTComponentHandler();
9367             }
9368             if (accessibleAWTFocusHandler == null) {
9369                 accessibleAWTFocusHandler = new AccessibleAWTFocusHandler();
9370             }
9371             if (propertyListenersCount++ == 0) {
9372                 Component.this.addComponentListener(accessibleAWTComponentHandler);
9373                 Component.this.addFocusListener(accessibleAWTFocusHandler);
9374             }
9375             super.addPropertyChangeListener(listener);
9376         }
9377 
9378         /**
9379          * Remove a PropertyChangeListener from the listener list.
9380          * This removes a PropertyChangeListener that was registered
9381          * for all properties.
9382          *
9383          * @param listener  The PropertyChangeListener to be removed
9384          */
9385         public void removePropertyChangeListener(PropertyChangeListener listener) {
9386             if (--propertyListenersCount == 0) {
9387                 Component.this.removeComponentListener(accessibleAWTComponentHandler);
9388                 Component.this.removeFocusListener(accessibleAWTFocusHandler);
9389             }
9390             super.removePropertyChangeListener(listener);
9391         }
9392 
9393         // AccessibleContext methods
9394         //
9395         /**
9396          * Gets the accessible name of this object.  This should almost never
9397          * return {@code java.awt.Component.getName()},
9398          * as that generally isn't a localized name,
9399          * and doesn't have meaning for the user.  If the
9400          * object is fundamentally a text object (e.g. a menu item), the
9401          * accessible name should be the text of the object (e.g. "save").
9402          * If the object has a tooltip, the tooltip text may also be an
9403          * appropriate String to return.
9404          *
9405          * @return the localized name of the object -- can be
9406          *         {@code null} if this
9407          *         object does not have a name
9408          * @see javax.accessibility.AccessibleContext#setAccessibleName
9409          */
9410         public String getAccessibleName() {
9411             return accessibleName;
9412         }
9413 
9414         /**
9415          * Gets the accessible description of this object.  This should be
9416          * a concise, localized description of what this object is - what
9417          * is its meaning to the user.  If the object has a tooltip, the
9418          * tooltip text may be an appropriate string to return, assuming
9419          * it contains a concise description of the object (instead of just
9420          * the name of the object - e.g. a "Save" icon on a toolbar that
9421          * had "save" as the tooltip text shouldn't return the tooltip
9422          * text as the description, but something like "Saves the current
9423          * text document" instead).
9424          *
9425          * @return the localized description of the object -- can be
9426          *        {@code null} if this object does not have a description
9427          * @see javax.accessibility.AccessibleContext#setAccessibleDescription
9428          */
9429         public String getAccessibleDescription() {
9430             return accessibleDescription;
9431         }
9432 
9433         /**
9434          * Gets the role of this object.
9435          *
9436          * @return an instance of {@code AccessibleRole}
9437          *      describing the role of the object
9438          * @see javax.accessibility.AccessibleRole
9439          */
9440         public AccessibleRole getAccessibleRole() {
9441             return AccessibleRole.AWT_COMPONENT;
9442         }
9443 
9444         /**
9445          * Gets the state of this object.
9446          *
9447          * @return an instance of {@code AccessibleStateSet}
9448          *       containing the current state set of the object
9449          * @see javax.accessibility.AccessibleState
9450          */
9451         public AccessibleStateSet getAccessibleStateSet() {
9452             return Component.this.getAccessibleStateSet();
9453         }
9454 
9455         /**
9456          * Gets the {@code Accessible} parent of this object.
9457          * If the parent of this object implements {@code Accessible},
9458          * this method should simply return {@code getParent}.
9459          *
9460          * @return the {@code Accessible} parent of this
9461          *      object -- can be {@code null} if this
9462          *      object does not have an {@code Accessible} parent
9463          */
9464         public Accessible getAccessibleParent() {
9465             if (accessibleParent != null) {
9466                 return accessibleParent;
9467             } else {
9468                 Container parent = getParent();
9469                 if (parent instanceof Accessible) {
9470                     return (Accessible) parent;
9471                 }
9472             }
9473             return null;
9474         }
9475 
9476         /**
9477          * Gets the index of this object in its accessible parent.
9478          *
9479          * @return the index of this object in its parent; or -1 if this
9480          *    object does not have an accessible parent
9481          * @see #getAccessibleParent
9482          */
9483         public int getAccessibleIndexInParent() {
9484             return Component.this.getAccessibleIndexInParent();
9485         }
9486 
9487         /**
9488          * Returns the number of accessible children in the object.  If all
9489          * of the children of this object implement {@code Accessible},
9490          * then this method should return the number of children of this object.
9491          *
9492          * @return the number of accessible children in the object
9493          */
9494         public int getAccessibleChildrenCount() {
9495             return 0; // Components don't have children
9496         }
9497 
9498         /**
9499          * Returns the nth {@code Accessible} child of the object.
9500          *
9501          * @param i zero-based index of child
9502          * @return the nth {@code Accessible} child of the object
9503          */
9504         public Accessible getAccessibleChild(int i) {
9505             return null; // Components don't have children
9506         }
9507 
9508         /**
9509          * Returns the locale of this object.
9510          *
9511          * @return the locale of this object
9512          */
9513         public Locale getLocale() {
9514             return Component.this.getLocale();
9515         }
9516 
9517         /**
9518          * Gets the {@code AccessibleComponent} associated
9519          * with this object if one exists.
9520          * Otherwise return {@code null}.
9521          *
9522          * @return the component
9523          */
9524         public AccessibleComponent getAccessibleComponent() {
9525             return this;
9526         }
9527 
9528 
9529         // AccessibleComponent methods
9530         //
9531         /**
9532          * Gets the background color of this object.
9533          *
9534          * @return the background color, if supported, of the object;
9535          *      otherwise, {@code null}
9536          */
9537         public Color getBackground() {
9538             return Component.this.getBackground();
9539         }
9540 
9541         /**
9542          * Sets the background color of this object.
9543          * (For transparency, see {@code isOpaque}.)
9544          *
9545          * @param c the new {@code Color} for the background
9546          * @see Component#isOpaque
9547          */
9548         public void setBackground(Color c) {
9549             Component.this.setBackground(c);
9550         }
9551 
9552         /**
9553          * Gets the foreground color of this object.
9554          *
9555          * @return the foreground color, if supported, of the object;
9556          *     otherwise, {@code null}
9557          */
9558         public Color getForeground() {
9559             return Component.this.getForeground();
9560         }
9561 
9562         /**
9563          * Sets the foreground color of this object.
9564          *
9565          * @param c the new {@code Color} for the foreground
9566          */
9567         public void setForeground(Color c) {
9568             Component.this.setForeground(c);
9569         }
9570 
9571         /**
9572          * Gets the {@code Cursor} of this object.
9573          *
9574          * @return the {@code Cursor}, if supported,
9575          *     of the object; otherwise, {@code null}
9576          */
9577         public Cursor getCursor() {
9578             return Component.this.getCursor();
9579         }
9580 
9581         /**
9582          * Sets the {@code Cursor} of this object.
9583          * <p>
9584          * The method may have no visual effect if the Java platform
9585          * implementation and/or the native system do not support
9586          * changing the mouse cursor shape.
9587          * @param cursor the new {@code Cursor} for the object
9588          */
9589         public void setCursor(Cursor cursor) {
9590             Component.this.setCursor(cursor);
9591         }
9592 
9593         /**
9594          * Gets the {@code Font} of this object.
9595          *
9596          * @return the {@code Font}, if supported,
9597          *    for the object; otherwise, {@code null}
9598          */
9599         public Font getFont() {
9600             return Component.this.getFont();
9601         }
9602 
9603         /**
9604          * Sets the {@code Font} of this object.
9605          *
9606          * @param f the new {@code Font} for the object
9607          */
9608         public void setFont(Font f) {
9609             Component.this.setFont(f);
9610         }
9611 
9612         /**
9613          * Gets the {@code FontMetrics} of this object.
9614          *
9615          * @param f the {@code Font}
9616          * @return the {@code FontMetrics}, if supported,
9617          *     the object; otherwise, {@code null}
9618          * @see #getFont
9619          */
9620         public FontMetrics getFontMetrics(Font f) {
9621             if (f == null) {
9622                 return null;
9623             } else {
9624                 return Component.this.getFontMetrics(f);
9625             }
9626         }
9627 
9628         /**
9629          * Determines if the object is enabled.
9630          *
9631          * @return true if object is enabled; otherwise, false
9632          */
9633         public boolean isEnabled() {
9634             return Component.this.isEnabled();
9635         }
9636 
9637         /**
9638          * Sets the enabled state of the object.
9639          *
9640          * @param b if true, enables this object; otherwise, disables it
9641          */
9642         public void setEnabled(boolean b) {
9643             boolean old = Component.this.isEnabled();
9644             Component.this.setEnabled(b);
9645             if (b != old) {
9646                 if (accessibleContext != null) {
9647                     if (b) {
9648                         accessibleContext.firePropertyChange(
9649                                                              AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9650                                                              null, AccessibleState.ENABLED);
9651                     } else {
9652                         accessibleContext.firePropertyChange(
9653                                                              AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9654                                                              AccessibleState.ENABLED, null);
9655                     }
9656                 }
9657             }
9658         }
9659 
9660         /**
9661          * Determines if the object is visible.  Note: this means that the
9662          * object intends to be visible; however, it may not in fact be
9663          * showing on the screen because one of the objects that this object
9664          * is contained by is not visible.  To determine if an object is
9665          * showing on the screen, use {@code isShowing}.
9666          *
9667          * @return true if object is visible; otherwise, false
9668          */
9669         public boolean isVisible() {
9670             return Component.this.isVisible();
9671         }
9672 
9673         /**
9674          * Sets the visible state of the object.
9675          *
9676          * @param b if true, shows this object; otherwise, hides it
9677          */
9678         public void setVisible(boolean b) {
9679             boolean old = Component.this.isVisible();
9680             Component.this.setVisible(b);
9681             if (b != old) {
9682                 if (accessibleContext != null) {
9683                     if (b) {
9684                         accessibleContext.firePropertyChange(
9685                                                              AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9686                                                              null, AccessibleState.VISIBLE);
9687                     } else {
9688                         accessibleContext.firePropertyChange(
9689                                                              AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9690                                                              AccessibleState.VISIBLE, null);
9691                     }
9692                 }
9693             }
9694         }
9695 
9696         /**
9697          * Determines if the object is showing.  This is determined by checking
9698          * the visibility of the object and ancestors of the object.  Note:
9699          * this will return true even if the object is obscured by another
9700          * (for example, it happens to be underneath a menu that was pulled
9701          * down).
9702          *
9703          * @return true if object is showing; otherwise, false
9704          */
9705         public boolean isShowing() {
9706             return Component.this.isShowing();
9707         }
9708 
9709         /**
9710          * Checks whether the specified point is within this object's bounds,
9711          * where the point's x and y coordinates are defined to be relative to
9712          * the coordinate system of the object.
9713          *
9714          * @param p the {@code Point} relative to the
9715          *     coordinate system of the object
9716          * @return true if object contains {@code Point}; otherwise false
9717          */
9718         public boolean contains(Point p) {
9719             return Component.this.contains(p);
9720         }
9721 
9722         /**
9723          * Returns the location of the object on the screen.
9724          *
9725          * @return location of object on screen -- can be
9726          *    {@code null} if this object is not on the screen
9727          */
9728         public Point getLocationOnScreen() {
9729             synchronized (Component.this.getTreeLock()) {
9730                 if (Component.this.isShowing()) {
9731                     return Component.this.getLocationOnScreen();
9732                 } else {
9733                     return null;
9734                 }
9735             }
9736         }
9737 
9738         /**
9739          * Gets the location of the object relative to the parent in the form
9740          * of a point specifying the object's top-left corner in the screen's
9741          * coordinate space.
9742          *
9743          * @return an instance of Point representing the top-left corner of
9744          * the object's bounds in the coordinate space of the screen;
9745          * {@code null} if this object or its parent are not on the screen
9746          */
9747         public Point getLocation() {
9748             return Component.this.getLocation();
9749         }
9750 
9751         /**
9752          * Sets the location of the object relative to the parent.
9753          * @param p  the coordinates of the object
9754          */
9755         public void setLocation(Point p) {
9756             Component.this.setLocation(p);
9757         }
9758 
9759         /**
9760          * Gets the bounds of this object in the form of a Rectangle object.
9761          * The bounds specify this object's width, height, and location
9762          * relative to its parent.
9763          *
9764          * @return a rectangle indicating this component's bounds;
9765          *   {@code null} if this object is not on the screen
9766          */
9767         public Rectangle getBounds() {
9768             return Component.this.getBounds();
9769         }
9770 
9771         /**
9772          * Sets the bounds of this object in the form of a
9773          * {@code Rectangle} object.
9774          * The bounds specify this object's width, height, and location
9775          * relative to its parent.
9776          *
9777          * @param r a rectangle indicating this component's bounds
9778          */
9779         public void setBounds(Rectangle r) {
9780             Component.this.setBounds(r);
9781         }
9782 
9783         /**
9784          * Returns the size of this object in the form of a
9785          * {@code Dimension} object. The height field of the
9786          * {@code Dimension} object contains this object's
9787          * height, and the width field of the {@code Dimension}
9788          * object contains this object's width.
9789          *
9790          * @return a {@code Dimension} object that indicates
9791          *     the size of this component; {@code null} if
9792          *     this object is not on the screen
9793          */
9794         public Dimension getSize() {
9795             return Component.this.getSize();
9796         }
9797 
9798         /**
9799          * Resizes this object so that it has width and height.
9800          *
9801          * @param d the dimension specifying the new size of the object
9802          */
9803         public void setSize(Dimension d) {
9804             Component.this.setSize(d);
9805         }
9806 
9807         /**
9808          * Returns the {@code Accessible} child,
9809          * if one exists, contained at the local
9810          * coordinate {@code Point}.  Otherwise returns
9811          * {@code null}.
9812          *
9813          * @param p the point defining the top-left corner of
9814          *      the {@code Accessible}, given in the
9815          *      coordinate space of the object's parent
9816          * @return the {@code Accessible}, if it exists,
9817          *      at the specified location; else {@code null}
9818          */
9819         public Accessible getAccessibleAt(Point p) {
9820             return null; // Components don't have children
9821         }
9822 
9823         /**
9824          * Returns whether this object can accept focus or not.
9825          *
9826          * @return true if object can accept focus; otherwise false
9827          */
9828         public boolean isFocusTraversable() {
9829             return Component.this.isFocusTraversable();
9830         }
9831 
9832         /**
9833          * Requests focus for this object.
9834          */
9835         public void requestFocus() {
9836             Component.this.requestFocus();
9837         }
9838 
9839         /**
9840          * Adds the specified focus listener to receive focus events from this
9841          * component.
9842          *
9843          * @param l the focus listener
9844          */
9845         public void addFocusListener(FocusListener l) {
9846             Component.this.addFocusListener(l);
9847         }
9848 
9849         /**
9850          * Removes the specified focus listener so it no longer receives focus
9851          * events from this component.
9852          *
9853          * @param l the focus listener
9854          */
9855         public void removeFocusListener(FocusListener l) {
9856             Component.this.removeFocusListener(l);
9857         }
9858 
9859     } // inner class AccessibleAWTComponent
9860 
9861 
9862     /**
9863      * Gets the index of this object in its accessible parent.
9864      * If this object does not have an accessible parent, returns
9865      * -1.
9866      *
9867      * @return the index of this object in its accessible parent
9868      */
9869     int getAccessibleIndexInParent() {
9870         synchronized (getTreeLock()) {
9871 
9872             AccessibleContext accContext = getAccessibleContext();
9873             if (accContext == null) {
9874                 return -1;
9875             }
9876 
9877             Accessible parent = accContext.getAccessibleParent();
9878             if (parent == null) {
9879                 return -1;
9880             }
9881 
9882             accContext = parent.getAccessibleContext();
9883             for (int i = 0; i < accContext.getAccessibleChildrenCount(); i++) {
9884                 if (this.equals(accContext.getAccessibleChild(i))) {
9885                     return i;
9886                 }
9887             }
9888 
9889             return -1;
9890         }
9891     }
9892 
9893     /**
9894      * Gets the current state set of this object.
9895      *
9896      * @return an instance of {@code AccessibleStateSet}
9897      *    containing the current state set of the object
9898      * @see AccessibleState
9899      */
9900     AccessibleStateSet getAccessibleStateSet() {
9901         synchronized (getTreeLock()) {
9902             AccessibleStateSet states = new AccessibleStateSet();
9903             if (this.isEnabled()) {
9904                 states.add(AccessibleState.ENABLED);
9905             }
9906             if (this.isFocusTraversable()) {
9907                 states.add(AccessibleState.FOCUSABLE);
9908             }
9909             if (this.isVisible()) {
9910                 states.add(AccessibleState.VISIBLE);
9911             }
9912             if (this.isShowing()) {
9913                 states.add(AccessibleState.SHOWING);
9914             }
9915             if (this.isFocusOwner()) {
9916                 states.add(AccessibleState.FOCUSED);
9917             }
9918             if (this instanceof Accessible) {
9919                 AccessibleContext ac = ((Accessible) this).getAccessibleContext();
9920                 if (ac != null) {
9921                     Accessible ap = ac.getAccessibleParent();
9922                     if (ap != null) {
9923                         AccessibleContext pac = ap.getAccessibleContext();
9924                         if (pac != null) {
9925                             AccessibleSelection as = pac.getAccessibleSelection();
9926                             if (as != null) {
9927                                 states.add(AccessibleState.SELECTABLE);
9928                                 int i = ac.getAccessibleIndexInParent();
9929                                 if (i >= 0) {
9930                                     if (as.isAccessibleChildSelected(i)) {
9931                                         states.add(AccessibleState.SELECTED);
9932                                     }
9933                                 }
9934                             }
9935                         }
9936                     }
9937                 }
9938             }
9939             if (Component.isInstanceOf(this, "javax.swing.JComponent")) {
9940                 if (((javax.swing.JComponent) this).isOpaque()) {
9941                     states.add(AccessibleState.OPAQUE);
9942                 }
9943             }
9944             return states;
9945         }
9946     }
9947 
9948     /**
9949      * Checks that the given object is instance of the given class.
9950      * @param obj Object to be checked
9951      * @param className The name of the class. Must be fully-qualified class name.
9952      * @return true, if this object is instanceof given class,
9953      *         false, otherwise, or if obj or className is null
9954      */
9955     static boolean isInstanceOf(Object obj, String className) {
9956         if (obj == null) return false;
9957         if (className == null) return false;
9958 
9959         Class<?> cls = obj.getClass();
9960         while (cls != null) {
9961             if (cls.getName().equals(className)) {
9962                 return true;
9963             }
9964             cls = cls.getSuperclass();
9965         }
9966         return false;
9967     }
9968 
9969 
9970     // ************************** MIXING CODE *******************************
9971 
9972     /**
9973      * Check whether we can trust the current bounds of the component.
9974      * The return value of false indicates that the container of the
9975      * component is invalid, and therefore needs to be laid out, which would
9976      * probably mean changing the bounds of its children.
9977      * Null-layout of the container or absence of the container mean
9978      * the bounds of the component are final and can be trusted.
9979      */
9980     final boolean areBoundsValid() {
9981         Container cont = getContainer();
9982         return cont == null || cont.isValid() || cont.getLayout() == null;
9983     }
9984 
9985     /**
9986      * Applies the shape to the component
9987      * @param shape Shape to be applied to the component
9988      */
9989     void applyCompoundShape(Region shape) {
9990         checkTreeLock();
9991 
9992         if (!areBoundsValid()) {
9993             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
9994                 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid());
9995             }
9996             return;
9997         }
9998 
9999         if (!isLightweight()) {
10000             ComponentPeer peer = this.peer;
10001             if (peer != null) {
10002                 // The Region class has some optimizations. That's why
10003                 // we should manually check whether it's empty and
10004                 // substitute the object ourselves. Otherwise we end up
10005                 // with some incorrect Region object with loX being
10006                 // greater than the hiX for instance.
10007                 if (shape.isEmpty()) {
10008                     shape = Region.EMPTY_REGION;
10009                 }
10010 
10011 
10012                 // Note: the shape is not really copied/cloned. We create
10013                 // the Region object ourselves, so there's no any possibility
10014                 // to modify the object outside of the mixing code.
10015                 // Nullifying compoundShape means that the component has normal shape
10016                 // (or has no shape at all).
10017                 if (shape.equals(getNormalShape())) {
10018                     if (this.compoundShape == null) {
10019                         return;
10020                     }
10021                     this.compoundShape = null;
10022                     peer.applyShape(null);
10023                 } else {
10024                     if (shape.equals(getAppliedShape())) {
10025                         return;
10026                     }
10027                     this.compoundShape = shape;
10028                     Point compAbsolute = getLocationOnWindow();
10029                     if (mixingLog.isLoggable(PlatformLogger.Level.FINER)) {
10030                         mixingLog.fine("this = " + this +
10031                                 "; compAbsolute=" + compAbsolute + "; shape=" + shape);
10032                     }
10033                     peer.applyShape(shape.getTranslatedRegion(-compAbsolute.x, -compAbsolute.y));
10034                 }
10035             }
10036         }
10037     }
10038 
10039     /**
10040      * Returns the shape previously set with applyCompoundShape().
10041      * If the component is LW or no shape was applied yet,
10042      * the method returns the normal shape.
10043      */
10044     private Region getAppliedShape() {
10045         checkTreeLock();
10046         //XXX: if we allow LW components to have a shape, this must be changed
10047         return (this.compoundShape == null || isLightweight()) ? getNormalShape() : this.compoundShape;
10048     }
10049 
10050     Point getLocationOnWindow() {
10051         checkTreeLock();
10052         Point curLocation = getLocation();
10053 
10054         for (Container parent = getContainer();
10055                 parent != null && !(parent instanceof Window);
10056                 parent = parent.getContainer())
10057         {
10058             curLocation.x += parent.getX();
10059             curLocation.y += parent.getY();
10060         }
10061 
10062         return curLocation;
10063     }
10064 
10065     /**
10066      * Returns the full shape of the component located in window coordinates
10067      */
10068     final Region getNormalShape() {
10069         checkTreeLock();
10070         //XXX: we may take into account a user-specified shape for this component
10071         Point compAbsolute = getLocationOnWindow();
10072         return
10073             Region.getInstanceXYWH(
10074                     compAbsolute.x,
10075                     compAbsolute.y,
10076                     getWidth(),
10077                     getHeight()
10078             );
10079     }
10080 
10081     /**
10082      * Returns the "opaque shape" of the component.
10083      *
10084      * The opaque shape of a lightweight components is the actual shape that
10085      * needs to be cut off of the heavyweight components in order to mix this
10086      * lightweight component correctly with them.
10087      *
10088      * The method is overriden in the java.awt.Container to handle non-opaque
10089      * containers containing opaque children.
10090      *
10091      * See 6637655 for details.
10092      */
10093     Region getOpaqueShape() {
10094         checkTreeLock();
10095         if (mixingCutoutRegion != null) {
10096             return mixingCutoutRegion;
10097         } else {
10098             return getNormalShape();
10099         }
10100     }
10101 
10102     final int getSiblingIndexAbove() {
10103         checkTreeLock();
10104         Container parent = getContainer();
10105         if (parent == null) {
10106             return -1;
10107         }
10108 
10109         int nextAbove = parent.getComponentZOrder(this) - 1;
10110 
10111         return nextAbove < 0 ? -1 : nextAbove;
10112     }
10113 
10114     final ComponentPeer getHWPeerAboveMe() {
10115         checkTreeLock();
10116 
10117         Container cont = getContainer();
10118         int indexAbove = getSiblingIndexAbove();
10119 
10120         while (cont != null) {
10121             for (int i = indexAbove; i > -1; i--) {
10122                 Component comp = cont.getComponent(i);
10123                 if (comp != null && comp.isDisplayable() && !comp.isLightweight()) {
10124                     return comp.peer;
10125                 }
10126             }
10127             // traversing the hierarchy up to the closest HW container;
10128             // further traversing may return a component that is not actually
10129             // a native sibling of this component and this kind of z-order
10130             // request may not be allowed by the underlying system (6852051).
10131             if (!cont.isLightweight()) {
10132                 break;
10133             }
10134 
10135             indexAbove = cont.getSiblingIndexAbove();
10136             cont = cont.getContainer();
10137         }
10138 
10139         return null;
10140     }
10141 
10142     final int getSiblingIndexBelow() {
10143         checkTreeLock();
10144         Container parent = getContainer();
10145         if (parent == null) {
10146             return -1;
10147         }
10148 
10149         int nextBelow = parent.getComponentZOrder(this) + 1;
10150 
10151         return nextBelow >= parent.getComponentCount() ? -1 : nextBelow;
10152     }
10153 
10154     final boolean isNonOpaqueForMixing() {
10155         return mixingCutoutRegion != null &&
10156             mixingCutoutRegion.isEmpty();
10157     }
10158 
10159     private Region calculateCurrentShape() {
10160         checkTreeLock();
10161         Region s = getNormalShape();
10162 
10163         if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10164             mixingLog.fine("this = " + this + "; normalShape=" + s);
10165         }
10166 
10167         if (getContainer() != null) {
10168             Component comp = this;
10169             Container cont = comp.getContainer();
10170 
10171             while (cont != null) {
10172                 for (int index = comp.getSiblingIndexAbove(); index != -1; --index) {
10173                     /* It is assumed that:
10174                      *
10175                      *    getComponent(getContainer().getComponentZOrder(comp)) == comp
10176                      *
10177                      * The assumption has been made according to the current
10178                      * implementation of the Container class.
10179                      */
10180                     Component c = cont.getComponent(index);
10181                     if (c.isLightweight() && c.isShowing()) {
10182                         s = s.getDifference(c.getOpaqueShape());
10183                     }
10184                 }
10185 
10186                 if (cont.isLightweight()) {
10187                     s = s.getIntersection(cont.getNormalShape());
10188                 } else {
10189                     break;
10190                 }
10191 
10192                 comp = cont;
10193                 cont = cont.getContainer();
10194             }
10195         }
10196 
10197         if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10198             mixingLog.fine("currentShape=" + s);
10199         }
10200 
10201         return s;
10202     }
10203 
10204     void applyCurrentShape() {
10205         checkTreeLock();
10206         if (!areBoundsValid()) {
10207             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10208                 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid());
10209             }
10210             return; // Because applyCompoundShape() ignores such components anyway
10211         }
10212         if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10213             mixingLog.fine("this = " + this);
10214         }
10215         applyCompoundShape(calculateCurrentShape());
10216     }
10217 
10218     final void subtractAndApplyShape(Region s) {
10219         checkTreeLock();
10220 
10221         if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10222             mixingLog.fine("this = " + this + "; s=" + s);
10223         }
10224 
10225         applyCompoundShape(getAppliedShape().getDifference(s));
10226     }
10227 
10228     private final void applyCurrentShapeBelowMe() {
10229         checkTreeLock();
10230         Container parent = getContainer();
10231         if (parent != null && parent.isShowing()) {
10232             // First, reapply shapes of my siblings
10233             parent.recursiveApplyCurrentShape(getSiblingIndexBelow());
10234 
10235             // Second, if my container is non-opaque, reapply shapes of siblings of my container
10236             Container parent2 = parent.getContainer();
10237             while (!parent.isOpaque() && parent2 != null) {
10238                 parent2.recursiveApplyCurrentShape(parent.getSiblingIndexBelow());
10239 
10240                 parent = parent2;
10241                 parent2 = parent.getContainer();
10242             }
10243         }
10244     }
10245 
10246     final void subtractAndApplyShapeBelowMe() {
10247         checkTreeLock();
10248         Container parent = getContainer();
10249         if (parent != null && isShowing()) {
10250             Region opaqueShape = getOpaqueShape();
10251 
10252             // First, cut my siblings
10253             parent.recursiveSubtractAndApplyShape(opaqueShape, getSiblingIndexBelow());
10254 
10255             // Second, if my container is non-opaque, cut siblings of my container
10256             Container parent2 = parent.getContainer();
10257             while (!parent.isOpaque() && parent2 != null) {
10258                 parent2.recursiveSubtractAndApplyShape(opaqueShape, parent.getSiblingIndexBelow());
10259 
10260                 parent = parent2;
10261                 parent2 = parent.getContainer();
10262             }
10263         }
10264     }
10265 
10266     void mixOnShowing() {
10267         synchronized (getTreeLock()) {
10268             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10269                 mixingLog.fine("this = " + this);
10270             }
10271             if (!isMixingNeeded()) {
10272                 return;
10273             }
10274             if (isLightweight()) {
10275                 subtractAndApplyShapeBelowMe();
10276             } else {
10277                 applyCurrentShape();
10278             }
10279         }
10280     }
10281 
10282     void mixOnHiding(boolean isLightweight) {
10283         // We cannot be sure that the peer exists at this point, so we need the argument
10284         //    to find out whether the hiding component is (well, actually was) a LW or a HW.
10285         synchronized (getTreeLock()) {
10286             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10287                 mixingLog.fine("this = " + this + "; isLightweight = " + isLightweight);
10288             }
10289             if (!isMixingNeeded()) {
10290                 return;
10291             }
10292             if (isLightweight) {
10293                 applyCurrentShapeBelowMe();
10294             }
10295         }
10296     }
10297 
10298     void mixOnReshaping() {
10299         synchronized (getTreeLock()) {
10300             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10301                 mixingLog.fine("this = " + this);
10302             }
10303             if (!isMixingNeeded()) {
10304                 return;
10305             }
10306             if (isLightweight()) {
10307                 applyCurrentShapeBelowMe();
10308             } else {
10309                 applyCurrentShape();
10310             }
10311         }
10312     }
10313 
10314     void mixOnZOrderChanging(int oldZorder, int newZorder) {
10315         synchronized (getTreeLock()) {
10316             boolean becameHigher = newZorder < oldZorder;
10317             Container parent = getContainer();
10318 
10319             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10320                 mixingLog.fine("this = " + this +
10321                     "; oldZorder=" + oldZorder + "; newZorder=" + newZorder + "; parent=" + parent);
10322             }
10323             if (!isMixingNeeded()) {
10324                 return;
10325             }
10326             if (isLightweight()) {
10327                 if (becameHigher) {
10328                     if (parent != null && isShowing()) {
10329                         parent.recursiveSubtractAndApplyShape(getOpaqueShape(), getSiblingIndexBelow(), oldZorder);
10330                     }
10331                 } else {
10332                     if (parent != null) {
10333                         parent.recursiveApplyCurrentShape(oldZorder, newZorder);
10334                     }
10335                 }
10336             } else {
10337                 if (becameHigher) {
10338                     applyCurrentShape();
10339                 } else {
10340                     if (parent != null) {
10341                         Region shape = getAppliedShape();
10342 
10343                         for (int index = oldZorder; index < newZorder; index++) {
10344                             Component c = parent.getComponent(index);
10345                             if (c.isLightweight() && c.isShowing()) {
10346                                 shape = shape.getDifference(c.getOpaqueShape());
10347                             }
10348                         }
10349                         applyCompoundShape(shape);
10350                     }
10351                 }
10352             }
10353         }
10354     }
10355 
10356     void mixOnValidating() {
10357         // This method gets overriden in the Container. Obviously, a plain
10358         // non-container components don't need to handle validation.
10359     }
10360 
10361     final boolean isMixingNeeded() {
10362         if (SunToolkit.getSunAwtDisableMixing()) {
10363             if (mixingLog.isLoggable(PlatformLogger.Level.FINEST)) {
10364                 mixingLog.finest("this = " + this + "; Mixing disabled via sun.awt.disableMixing");
10365             }
10366             return false;
10367         }
10368         if (!areBoundsValid()) {
10369             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10370                 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid());
10371             }
10372             return false;
10373         }
10374         Window window = getContainingWindow();
10375         if (window != null) {
10376             if (!window.hasHeavyweightDescendants() || !window.hasLightweightDescendants() || window.isDisposing()) {
10377                 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10378                     mixingLog.fine("containing window = " + window +
10379                             "; has h/w descendants = " + window.hasHeavyweightDescendants() +
10380                             "; has l/w descendants = " + window.hasLightweightDescendants() +
10381                             "; disposing = " + window.isDisposing());
10382                 }
10383                 return false;
10384             }
10385         } else {
10386             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10387                 mixingLog.fine("this = " + this + "; containing window is null");
10388             }
10389             return false;
10390         }
10391         return true;
10392     }
10393 
10394     /**
10395      * Sets a 'mixing-cutout' shape for this lightweight component.
10396      *
10397      * This method is used exclusively for the purposes of the
10398      * Heavyweight/Lightweight Components Mixing feature and will
10399      * have no effect if applied to a heavyweight component.
10400      *
10401      * By default a lightweight component is treated as an opaque rectangle for
10402      * the purposes of the Heavyweight/Lightweight Components Mixing feature.
10403      * This method enables developers to set an arbitrary shape to be cut out
10404      * from heavyweight components positioned underneath the lightweight
10405      * component in the z-order.
10406      * <p>
10407      * The {@code shape} argument may have the following values:
10408      * <ul>
10409      * <li>{@code null} - reverts the default cutout shape (the rectangle equal
10410      * to the component's {@code getBounds()})
10411      * <li><i>empty-shape</i> - does not cut out anything from heavyweight
10412      * components. This makes this lightweight component effectively
10413      * transparent. Note that descendants of the lightweight component still
10414      * affect the shapes of heavyweight components.  An example of an
10415      * <i>empty-shape</i> is {@code new Rectangle()}.
10416      * <li><i>non-empty-shape</i> - the given shape will be cut out from
10417      * heavyweight components.
10418      * </ul>
10419      * <p>
10420      * The most common example when the 'mixing-cutout' shape is needed is a
10421      * glass pane component. The {@link JRootPane#setGlassPane} method
10422      * automatically sets the <i>empty-shape</i> as the 'mixing-cutout' shape
10423      * for the given glass pane component.  If a developer needs some other
10424      * 'mixing-cutout' shape for the glass pane (which is rare), this must be
10425      * changed manually after installing the glass pane to the root pane.
10426      *
10427      * @param shape the new 'mixing-cutout' shape
10428      * @since 9
10429      */
10430     public void setMixingCutoutShape(Shape shape) {
10431         Region region = shape == null ? null : Region.getInstance(shape, null);
10432 
10433         synchronized (getTreeLock()) {
10434             boolean needShowing = false;
10435             boolean needHiding = false;
10436 
10437             if (!isNonOpaqueForMixing()) {
10438                 needHiding = true;
10439             }
10440 
10441             mixingCutoutRegion = region;
10442 
10443             if (!isNonOpaqueForMixing()) {
10444                 needShowing = true;
10445             }
10446 
10447             if (isMixingNeeded()) {
10448                 if (needHiding) {
10449                     mixOnHiding(isLightweight());
10450                 }
10451                 if (needShowing) {
10452                     mixOnShowing();
10453                 }
10454             }
10455         }
10456     }
10457 
10458     // ****************** END OF MIXING CODE ********************************
10459 
10460     // Note that the method is overriden in the Window class,
10461     // a window doesn't need to be updated in the Z-order.
10462     void updateZOrder() {
10463         peer.setZOrder(getHWPeerAboveMe());
10464     }
10465 
10466 }