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