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