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