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