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