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