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