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