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