1 /*
   2  * Copyright (c) 1995, 2014, 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.CausedFocusEvent;
  71 import sun.awt.EmbeddedFrame;
  72 import sun.awt.dnd.SunDropTargetEvent;
  73 import sun.awt.im.CompositionArea;
  74 import sun.font.FontManager;
  75 import sun.font.FontManagerFactory;
  76 import sun.font.SunFontManager;
  77 import sun.java2d.SunGraphics2D;
  78 import sun.java2d.pipe.Region;
  79 import sun.awt.image.VSyncedBSManager;
  80 import sun.java2d.pipe.hw.ExtendedBufferCapabilities;
  81 import static sun.java2d.pipe.hw.ExtendedBufferCapabilities.VSyncType.*;
  82 import sun.awt.RequestFocusController;
  83 import sun.java2d.SunGraphicsEnvironment;
  84 import sun.util.logging.PlatformLogger;
  85 
  86 /**
  87  * A <em>component</em> is an object having a graphical representation
  88  * that can be displayed on the screen and that can interact with the
  89  * user. Examples of components are the buttons, checkboxes, and scrollbars
  90  * of a typical graphical user interface. <p>
  91  * The <code>Component</code> class is the abstract superclass of
  92  * the nonmenu-related Abstract Window Toolkit components. Class
  93  * <code>Component</code> can also be extended directly to create a
  94  * lightweight component. A lightweight component is a component that is
  95  * not associated with a native window. On the contrary, a heavyweight
  96  * component is associated with a native window. The {@link #isLightweight()}
  97  * method may be used to distinguish between the two kinds of the components.
  98  * <p>
  99  * Lightweight and heavyweight components may be mixed in a single component
 100  * hierarchy. However, for correct operating of such a mixed hierarchy of
 101  * components, the whole hierarchy must be valid. When the hierarchy gets
 102  * invalidated, like after changing the bounds of components, or
 103  * adding/removing components to/from containers, the whole hierarchy must be
 104  * validated afterwards by means of the {@link Container#validate()} method
 105  * invoked on the top-most invalid container of the hierarchy.
 106  *
 107  * <h3>Serialization</h3>
 108  * It is important to note that only AWT listeners which conform
 109  * to the <code>Serializable</code> protocol will be saved when
 110  * the object is stored.  If an AWT object has listeners that
 111  * aren't marked serializable, they will be dropped at
 112  * <code>writeObject</code> time.  Developers will need, as always,
 113  * to consider the implications of making an object serializable.
 114  * One situation to watch out for is this:
 115  * <pre>
 116  *    import java.awt.*;
 117  *    import java.awt.event.*;
 118  *    import java.io.Serializable;
 119  *
 120  *    class MyApp implements ActionListener, Serializable
 121  *    {
 122  *        BigObjectThatShouldNotBeSerializedWithAButton bigOne;
 123  *        Button aButton = new Button();
 124  *
 125  *        MyApp()
 126  *        {
 127  *            // Oops, now aButton has a listener with a reference
 128  *            // to bigOne!
 129  *            aButton.addActionListener(this);
 130  *        }
 131  *
 132  *        public void actionPerformed(ActionEvent e)
 133  *        {
 134  *            System.out.println("Hello There");
 135  *        }
 136  *    }
 137  * </pre>
 138  * In this example, serializing <code>aButton</code> by itself
 139  * will cause <code>MyApp</code> and everything it refers to
 140  * to be serialized as well.  The problem is that the listener
 141  * is serializable by coincidence, not by design.  To separate
 142  * the decisions about <code>MyApp</code> and the
 143  * <code>ActionListener</code> being serializable one can use a
 144  * nested class, as in the following example:
 145  * <pre>
 146  *    import java.awt.*;
 147  *    import java.awt.event.*;
 148  *    import java.io.Serializable;
 149  *
 150  *    class MyApp implements java.io.Serializable
 151  *    {
 152  *         BigObjectThatShouldNotBeSerializedWithAButton bigOne;
 153  *         Button aButton = new Button();
 154  *
 155  *         static class MyActionListener implements ActionListener
 156  *         {
 157  *             public void actionPerformed(ActionEvent e)
 158  *             {
 159  *                 System.out.println("Hello There");
 160  *             }
 161  *         }
 162  *
 163  *         MyApp()
 164  *         {
 165  *             aButton.addActionListener(new MyActionListener());
 166  *         }
 167  *    }
 168  * </pre>
 169  * <p>
 170  * <b>Note</b>: For more information on the paint mechanisms utilitized
 171  * by AWT and Swing, including information on how to write the most
 172  * efficient painting code, see
 173  * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
 174  * <p>
 175  * For details on the focus subsystem, see
 176  * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
 177  * How to Use the Focus Subsystem</a>,
 178  * a section in <em>The Java Tutorial</em>, and the
 179  * <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
 180  * for more information.
 181  *
 182  * @author      Arthur van Hoff
 183  * @author      Sami Shaio
 184  */
 185 public abstract class Component implements ImageObserver, MenuContainer,
 186                                            Serializable
 187 {
 188 
 189     private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.Component");
 190     private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.Component");
 191     private static final PlatformLogger focusLog = PlatformLogger.getLogger("java.awt.focus.Component");
 192     private static final PlatformLogger mixingLog = PlatformLogger.getLogger("java.awt.mixing.Component");
 193 
 194     /**
 195      * The peer of the component. The peer implements the component's
 196      * behavior. The peer is set when the <code>Component</code> is
 197      * added to a container that also is a peer.
 198      * @see #addNotify
 199      * @see #removeNotify
 200      */
 201     transient ComponentPeer peer;
 202 
 203     /**
 204      * The parent of the object. It may be <code>null</code>
 205      * for top-level components.
 206      * @see #getParent
 207      */
 208     transient Container parent;
 209 
 210     /**
 211      * The <code>AppContext</code> of the component. Applets/Plugin may
 212      * change the AppContext.
 213      */
 214     transient AppContext appContext;
 215 
 216     /**
 217      * The x position of the component in the parent's coordinate system.
 218      *
 219      * @serial
 220      * @see #getLocation
 221      */
 222     int x;
 223 
 224     /**
 225      * The y position of the component in the parent's coordinate system.
 226      *
 227      * @serial
 228      * @see #getLocation
 229      */
 230     int y;
 231 
 232     /**
 233      * The width of the component.
 234      *
 235      * @serial
 236      * @see #getSize
 237      */
 238     int width;
 239 
 240     /**
 241      * The height of the component.
 242      *
 243      * @serial
 244      * @see #getSize
 245      */
 246     int height;
 247 
 248     /**
 249      * The foreground color for this component.
 250      * <code>foreground</code> can be <code>null</code>.
 251      *
 252      * @serial
 253      * @see #getForeground
 254      * @see #setForeground
 255      */
 256     Color       foreground;
 257 
 258     /**
 259      * The background color for this component.
 260      * <code>background</code> can be <code>null</code>.
 261      *
 262      * @serial
 263      * @see #getBackground
 264      * @see #setBackground
 265      */
 266     Color       background;
 267 
 268     /**
 269      * The font used by this component.
 270      * The <code>font</code> can be <code>null</code>.
 271      *
 272      * @serial
 273      * @see #getFont
 274      * @see #setFont
 275      */
 276     volatile Font font;
 277 
 278     /**
 279      * The font which the peer is currently using.
 280      * (<code>null</code> if no peer exists.)
 281      */
 282     Font        peerFont;
 283 
 284     /**
 285      * The cursor displayed when pointer is over this component.
 286      * This value can be <code>null</code>.
 287      *
 288      * @serial
 289      * @see #getCursor
 290      * @see #setCursor
 291      */
 292     Cursor      cursor;
 293 
 294     /**
 295      * The locale for the component.
 296      *
 297      * @serial
 298      * @see #getLocale
 299      * @see #setLocale
 300      */
 301     Locale      locale;
 302 
 303     /**
 304      * A reference to a <code>GraphicsConfiguration</code> object
 305      * used to describe the characteristics of a graphics
 306      * destination.
 307      * This value can be <code>null</code>.
 308      *
 309      * @since 1.3
 310      * @serial
 311      * @see GraphicsConfiguration
 312      * @see #getGraphicsConfiguration
 313      */
 314     private transient GraphicsConfiguration graphicsConfig = null;
 315 
 316     /**
 317      * A reference to a <code>BufferStrategy</code> object
 318      * used to manipulate the buffers on this component.
 319      *
 320      * @since 1.4
 321      * @see java.awt.image.BufferStrategy
 322      * @see #getBufferStrategy()
 323      */
 324     transient BufferStrategy bufferStrategy = null;
 325 
 326     /**
 327      * True when the object should ignore all repaint events.
 328      *
 329      * @since 1.4
 330      * @serial
 331      * @see #setIgnoreRepaint
 332      * @see #getIgnoreRepaint
 333      */
 334     boolean ignoreRepaint = false;
 335 
 336     /**
 337      * True when the object is visible. An object that is not
 338      * visible is not drawn on the screen.
 339      *
 340      * @serial
 341      * @see #isVisible
 342      * @see #setVisible
 343      */
 344     boolean visible = true;
 345 
 346     /**
 347      * True when the object is enabled. An object that is not
 348      * enabled does not interact with the user.
 349      *
 350      * @serial
 351      * @see #isEnabled
 352      * @see #setEnabled
 353      */
 354     boolean enabled = true;
 355 
 356     /**
 357      * True when the object is valid. An invalid object needs to
 358      * be layed out. This flag is set to false when the object
 359      * size is changed.
 360      *
 361      * @serial
 362      * @see #isValid
 363      * @see #validate
 364      * @see #invalidate
 365      */
 366     private volatile boolean valid = false;
 367 
 368     /**
 369      * The <code>DropTarget</code> associated with this component.
 370      *
 371      * @since 1.2
 372      * @serial
 373      * @see #setDropTarget
 374      * @see #getDropTarget
 375      */
 376     DropTarget dropTarget;
 377 
 378     /**
 379      * @serial
 380      * @see #add
 381      */
 382     Vector<PopupMenu> popups;
 383 
 384     /**
 385      * A component's name.
 386      * This field can be <code>null</code>.
 387      *
 388      * @serial
 389      * @see #getName
 390      * @see #setName(String)
 391      */
 392     private String name;
 393 
 394     /**
 395      * A bool to determine whether the name has
 396      * been set explicitly. <code>nameExplicitlySet</code> will
 397      * be false if the name has not been set and
 398      * true if it has.
 399      *
 400      * @serial
 401      * @see #getName
 402      * @see #setName(String)
 403      */
 404     private boolean nameExplicitlySet = false;
 405 
 406     /**
 407      * Indicates whether this Component can be focused.
 408      *
 409      * @serial
 410      * @see #setFocusable
 411      * @see #isFocusable
 412      * @since 1.4
 413      */
 414     private boolean focusable = true;
 415 
 416     private static final int FOCUS_TRAVERSABLE_UNKNOWN = 0;
 417     private static final int FOCUS_TRAVERSABLE_DEFAULT = 1;
 418     private static final int FOCUS_TRAVERSABLE_SET = 2;
 419 
 420     /**
 421      * Tracks whether this Component is relying on default focus travesability.
 422      *
 423      * @serial
 424      * @since 1.4
 425      */
 426     private int isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN;
 427 
 428     /**
 429      * The focus traversal keys. These keys will generate focus traversal
 430      * behavior for Components for which focus traversal keys are enabled. If a
 431      * value of null is specified for a traversal key, this Component inherits
 432      * that traversal key from its parent. If all ancestors of this Component
 433      * have null specified for that traversal key, then the current
 434      * KeyboardFocusManager's default traversal key is used.
 435      *
 436      * @serial
 437      * @see #setFocusTraversalKeys
 438      * @see #getFocusTraversalKeys
 439      * @since 1.4
 440      */
 441     Set<AWTKeyStroke>[] focusTraversalKeys;
 442 
 443     private static final String[] focusTraversalKeyPropertyNames = {
 444         "forwardFocusTraversalKeys",
 445         "backwardFocusTraversalKeys",
 446         "upCycleFocusTraversalKeys",
 447         "downCycleFocusTraversalKeys"
 448     };
 449 
 450     /**
 451      * Indicates whether focus traversal keys are enabled for this Component.
 452      * Components for which focus traversal keys are disabled receive key
 453      * events for focus traversal keys. Components for which focus traversal
 454      * keys are enabled do not see these events; instead, the events are
 455      * automatically converted to traversal operations.
 456      *
 457      * @serial
 458      * @see #setFocusTraversalKeysEnabled
 459      * @see #getFocusTraversalKeysEnabled
 460      * @since 1.4
 461      */
 462     private boolean focusTraversalKeysEnabled = true;
 463 
 464     /**
 465      * The locking object for AWT component-tree and layout operations.
 466      *
 467      * @see #getTreeLock
 468      */
 469     static final Object LOCK = new AWTTreeLock();
 470     static class AWTTreeLock {}
 471 
 472     /*
 473      * The component's AccessControlContext.
 474      */
 475     private transient volatile AccessControlContext acc =
 476         AccessController.getContext();
 477 
 478     /**
 479      * Minimum size.
 480      * (This field perhaps should have been transient).
 481      *
 482      * @serial
 483      */
 484     Dimension minSize;
 485 
 486     /**
 487      * Whether or not setMinimumSize has been invoked with a non-null value.
 488      */
 489     boolean minSizeSet;
 490 
 491     /**
 492      * Preferred size.
 493      * (This field perhaps should have been transient).
 494      *
 495      * @serial
 496      */
 497     Dimension prefSize;
 498 
 499     /**
 500      * Whether or not setPreferredSize has been invoked with a non-null value.
 501      */
 502     boolean prefSizeSet;
 503 
 504     /**
 505      * Maximum size
 506      *
 507      * @serial
 508      */
 509     Dimension maxSize;
 510 
 511     /**
 512      * Whether or not setMaximumSize has been invoked with a non-null value.
 513      */
 514     boolean maxSizeSet;
 515 
 516     /**
 517      * The orientation for this component.
 518      * @see #getComponentOrientation
 519      * @see #setComponentOrientation
 520      */
 521     transient ComponentOrientation componentOrientation
 522     = ComponentOrientation.UNKNOWN;
 523 
 524     /**
 525      * <code>newEventsOnly</code> will be true if the event is
 526      * one of the event types enabled for the component.
 527      * It will then allow for normal processing to
 528      * continue.  If it is false the event is passed
 529      * to the component's parent and up the ancestor
 530      * tree until the event has been consumed.
 531      *
 532      * @serial
 533      * @see #dispatchEvent
 534      */
 535     boolean newEventsOnly = false;
 536     transient ComponentListener componentListener;
 537     transient FocusListener focusListener;
 538     transient HierarchyListener hierarchyListener;
 539     transient HierarchyBoundsListener hierarchyBoundsListener;
 540     transient KeyListener keyListener;
 541     transient MouseListener mouseListener;
 542     transient MouseMotionListener mouseMotionListener;
 543     transient MouseWheelListener mouseWheelListener;
 544     transient InputMethodListener inputMethodListener;
 545 
 546     /** Internal, constants for serialization */
 547     final static String actionListenerK = "actionL";
 548     final static String adjustmentListenerK = "adjustmentL";
 549     final static String componentListenerK = "componentL";
 550     final static String containerListenerK = "containerL";
 551     final static String focusListenerK = "focusL";
 552     final static String itemListenerK = "itemL";
 553     final static String keyListenerK = "keyL";
 554     final static String mouseListenerK = "mouseL";
 555     final static String mouseMotionListenerK = "mouseMotionL";
 556     final static String mouseWheelListenerK = "mouseWheelL";
 557     final static String textListenerK = "textL";
 558     final static String ownedWindowK = "ownedL";
 559     final static String windowListenerK = "windowL";
 560     final static String inputMethodListenerK = "inputMethodL";
 561     final static String hierarchyListenerK = "hierarchyL";
 562     final static String hierarchyBoundsListenerK = "hierarchyBoundsL";
 563     final static String windowStateListenerK = "windowStateL";
 564     final static String windowFocusListenerK = "windowFocusL";
 565 
 566     /**
 567      * The <code>eventMask</code> is ONLY set by subclasses via
 568      * <code>enableEvents</code>.
 569      * The mask should NOT be set when listeners are registered
 570      * so that we can distinguish the difference between when
 571      * listeners request events and subclasses request them.
 572      * One bit is used to indicate whether input methods are
 573      * enabled; this bit is set by <code>enableInputMethods</code> and is
 574      * on by default.
 575      *
 576      * @serial
 577      * @see #enableInputMethods
 578      * @see AWTEvent
 579      */
 580     long eventMask = AWTEvent.INPUT_METHODS_ENABLED_MASK;
 581 
 582     /**
 583      * Static properties for incremental drawing.
 584      * @see #imageUpdate
 585      */
 586     static boolean isInc;
 587     static int incRate;
 588     static {
 589         /* ensure that the necessary native libraries are loaded */
 590         Toolkit.loadLibraries();
 591         /* initialize JNI field and method ids */
 592         if (!GraphicsEnvironment.isHeadless()) {
 593             initIDs();
 594         }
 595 
 596         String s = java.security.AccessController.doPrivileged(
 597                                                                new GetPropertyAction("awt.image.incrementaldraw"));
 598         isInc = (s == null || s.equals("true"));
 599 
 600         s = java.security.AccessController.doPrivileged(
 601                                                         new GetPropertyAction("awt.image.redrawrate"));
 602         incRate = (s != null) ? Integer.parseInt(s) : 100;
 603     }
 604 
 605     /**
 606      * Ease-of-use constant for <code>getAlignmentY()</code>.
 607      * Specifies an alignment to the top of the component.
 608      * @see     #getAlignmentY
 609      */
 610     public static final float TOP_ALIGNMENT = 0.0f;
 611 
 612     /**
 613      * Ease-of-use constant for <code>getAlignmentY</code> and
 614      * <code>getAlignmentX</code>. Specifies an alignment to
 615      * the center of the component
 616      * @see     #getAlignmentX
 617      * @see     #getAlignmentY
 618      */
 619     public static final float CENTER_ALIGNMENT = 0.5f;
 620 
 621     /**
 622      * Ease-of-use constant for <code>getAlignmentY</code>.
 623      * Specifies an alignment to the bottom of the component.
 624      * @see     #getAlignmentY
 625      */
 626     public static final float BOTTOM_ALIGNMENT = 1.0f;
 627 
 628     /**
 629      * Ease-of-use constant for <code>getAlignmentX</code>.
 630      * Specifies an alignment to the left side of the component.
 631      * @see     #getAlignmentX
 632      */
 633     public static final float LEFT_ALIGNMENT = 0.0f;
 634 
 635     /**
 636      * Ease-of-use constant for <code>getAlignmentX</code>.
 637      * Specifies an alignment to the right side of the component.
 638      * @see     #getAlignmentX
 639      */
 640     public static final float RIGHT_ALIGNMENT = 1.0f;
 641 
 642     /*
 643      * JDK 1.1 serialVersionUID
 644      */
 645     private static final long serialVersionUID = -7644114512714619750L;
 646 
 647     /**
 648      * If any <code>PropertyChangeListeners</code> have been registered,
 649      * the <code>changeSupport</code> field describes them.
 650      *
 651      * @serial
 652      * @since 1.2
 653      * @see #addPropertyChangeListener
 654      * @see #removePropertyChangeListener
 655      * @see #firePropertyChange
 656      */
 657     private PropertyChangeSupport changeSupport;
 658 
 659     /*
 660      * In some cases using "this" as an object to synchronize by
 661      * can lead to a deadlock if client code also uses synchronization
 662      * by a component object. For every such situation revealed we should
 663      * consider possibility of replacing "this" with the package private
 664      * objectLock object introduced below. So far there're 3 issues known:
 665      * - CR 6708322 (the getName/setName methods);
 666      * - CR 6608764 (the PropertyChangeListener machinery);
 667      * - CR 7108598 (the Container.paint/KeyboardFocusManager.clearMostRecentFocusOwner methods).
 668      *
 669      * Note: this field is considered final, though readObject() prohibits
 670      * initializing final fields.
 671      */
 672     private transient Object objectLock = new Object();
 673     Object getObjectLock() {
 674         return objectLock;
 675     }
 676 
 677     /*
 678      * Returns the acc this component was constructed with.
 679      */
 680     final AccessControlContext getAccessControlContext() {
 681         if (acc == null) {
 682             throw new SecurityException("Component is missing AccessControlContext");
 683         }
 684         return acc;
 685     }
 686 
 687     boolean isPacked = false;
 688 
 689     /**
 690      * Pseudoparameter for direct Geometry API (setLocation, setBounds setSize
 691      * to signal setBounds what's changing. Should be used under TreeLock.
 692      * This is only needed due to the inability to change the cross-calling
 693      * order of public and deprecated methods.
 694      */
 695     private int boundsOp = ComponentPeer.DEFAULT_OPERATION;
 696 
 697     /**
 698      * Enumeration of the common ways the baseline of a component can
 699      * change as the size changes.  The baseline resize behavior is
 700      * primarily for layout managers that need to know how the
 701      * position of the baseline changes as the component size changes.
 702      * In general the baseline resize behavior will be valid for sizes
 703      * greater than or equal to the minimum size (the actual minimum
 704      * size; not a developer specified minimum size).  For sizes
 705      * smaller than the minimum size the baseline may change in a way
 706      * other than the baseline resize behavior indicates.  Similarly,
 707      * as the size approaches <code>Integer.MAX_VALUE</code> and/or
 708      * <code>Short.MAX_VALUE</code> the baseline may change in a way
 709      * other than the baseline resize behavior indicates.
 710      *
 711      * @see #getBaselineResizeBehavior
 712      * @see #getBaseline(int,int)
 713      * @since 1.6
 714      */
 715     public enum BaselineResizeBehavior {
 716         /**
 717          * Indicates the baseline remains fixed relative to the
 718          * y-origin.  That is, <code>getBaseline</code> returns
 719          * the same value regardless of the height or width.  For example, a
 720          * <code>JLabel</code> containing non-empty text with a
 721          * vertical alignment of <code>TOP</code> should have a
 722          * baseline type of <code>CONSTANT_ASCENT</code>.
 723          */
 724         CONSTANT_ASCENT,
 725 
 726         /**
 727          * Indicates the baseline remains fixed relative to the height
 728          * and does not change as the width is varied.  That is, for
 729          * any height H the difference between H and
 730          * <code>getBaseline(w, H)</code> is the same.  For example, a
 731          * <code>JLabel</code> containing non-empty text with a
 732          * vertical alignment of <code>BOTTOM</code> should have a
 733          * baseline type of <code>CONSTANT_DESCENT</code>.
 734          */
 735         CONSTANT_DESCENT,
 736 
 737         /**
 738          * Indicates the baseline remains a fixed distance from
 739          * the center of the component.  That is, for any height H the
 740          * difference between <code>getBaseline(w, H)</code> and
 741          * <code>H / 2</code> is the same (plus or minus one depending upon
 742          * rounding error).
 743          * <p>
 744          * Because of possible rounding errors it is recommended
 745          * you ask for the baseline with two consecutive heights and use
 746          * the return value to determine if you need to pad calculations
 747          * by 1.  The following shows how to calculate the baseline for
 748          * any height:
 749          * <pre>
 750          *   Dimension preferredSize = component.getPreferredSize();
 751          *   int baseline = getBaseline(preferredSize.width,
 752          *                              preferredSize.height);
 753          *   int nextBaseline = getBaseline(preferredSize.width,
 754          *                                  preferredSize.height + 1);
 755          *   // Amount to add to height when calculating where baseline
 756          *   // lands for a particular height:
 757          *   int padding = 0;
 758          *   // Where the baseline is relative to the mid point
 759          *   int baselineOffset = baseline - height / 2;
 760          *   if (preferredSize.height % 2 == 0 &amp;&amp;
 761          *       baseline != nextBaseline) {
 762          *       padding = 1;
 763          *   }
 764          *   else if (preferredSize.height % 2 == 1 &amp;&amp;
 765          *            baseline == nextBaseline) {
 766          *       baselineOffset--;
 767          *       padding = 1;
 768          *   }
 769          *   // The following calculates where the baseline lands for
 770          *   // the height z:
 771          *   int calculatedBaseline = (z + padding) / 2 + baselineOffset;
 772          * </pre>
 773          */
 774         CENTER_OFFSET,
 775 
 776         /**
 777          * Indicates the baseline resize behavior can not be expressed using
 778          * any of the other constants.  This may also indicate the baseline
 779          * varies with the width of the component.  This is also returned
 780          * by components that do not have a baseline.
 781          */
 782         OTHER
 783     }
 784 
 785     /*
 786      * The shape set with the applyCompoundShape() method. It uncludes the result
 787      * of the HW/LW mixing related shape computation. It may also include
 788      * the user-specified shape of the component.
 789      * The 'null' value means the component has normal shape (or has no shape at all)
 790      * and applyCompoundShape() will skip the following shape identical to normal.
 791      */
 792     private transient Region compoundShape = null;
 793 
 794     /*
 795      * Represents the shape of this lightweight component to be cut out from
 796      * heavyweight components should they intersect. Possible values:
 797      *    1. null - consider the shape rectangular
 798      *    2. EMPTY_REGION - nothing gets cut out (children still get cut out)
 799      *    3. non-empty - this shape gets cut out.
 800      */
 801     private transient Region mixingCutoutRegion = null;
 802 
 803     /*
 804      * Indicates whether addNotify() is complete
 805      * (i.e. the peer is created).
 806      */
 807     private transient boolean isAddNotifyComplete = false;
 808 
 809     /**
 810      * Should only be used in subclass getBounds to check that part of bounds
 811      * is actualy changing
 812      */
 813     int getBoundsOp() {
 814         assert Thread.holdsLock(getTreeLock());
 815         return boundsOp;
 816     }
 817 
 818     void setBoundsOp(int op) {
 819         assert Thread.holdsLock(getTreeLock());
 820         if (op == ComponentPeer.RESET_OPERATION) {
 821             boundsOp = ComponentPeer.DEFAULT_OPERATION;
 822         } else
 823             if (boundsOp == ComponentPeer.DEFAULT_OPERATION) {
 824                 boundsOp = op;
 825             }
 826     }
 827 
 828     // Whether this Component has had the background erase flag
 829     // specified via SunToolkit.disableBackgroundErase(). This is
 830     // needed in order to make this function work on X11 platforms,
 831     // where currently there is no chance to interpose on the creation
 832     // of the peer and therefore the call to XSetBackground.
 833     transient boolean backgroundEraseDisabled;
 834 
 835     static {
 836         AWTAccessor.setComponentAccessor(new AWTAccessor.ComponentAccessor() {
 837             public void setBackgroundEraseDisabled(Component comp, boolean disabled) {
 838                 comp.backgroundEraseDisabled = disabled;
 839             }
 840             public boolean getBackgroundEraseDisabled(Component comp) {
 841                 return comp.backgroundEraseDisabled;
 842             }
 843             public Rectangle getBounds(Component comp) {
 844                 return new Rectangle(comp.x, comp.y, comp.width, comp.height);
 845             }
 846             public void setMixingCutoutShape(Component comp, Shape shape) {
 847                 Region region = shape == null ?  null :
 848                     Region.getInstance(shape, null);
 849 
 850                 synchronized (comp.getTreeLock()) {
 851                     boolean needShowing = false;
 852                     boolean needHiding = false;
 853 
 854                     if (!comp.isNonOpaqueForMixing()) {
 855                         needHiding = true;
 856                     }
 857 
 858                     comp.mixingCutoutRegion = region;
 859 
 860                     if (!comp.isNonOpaqueForMixing()) {
 861                         needShowing = true;
 862                     }
 863 
 864                     if (comp.isMixingNeeded()) {
 865                         if (needHiding) {
 866                             comp.mixOnHiding(comp.isLightweight());
 867                         }
 868                         if (needShowing) {
 869                             comp.mixOnShowing();
 870                         }
 871                     }
 872                 }
 873             }
 874 
 875             public void setGraphicsConfiguration(Component comp,
 876                     GraphicsConfiguration gc)
 877             {
 878                 comp.setGraphicsConfiguration(gc);
 879             }
 880             public boolean requestFocus(Component comp, CausedFocusEvent.Cause cause) {
 881                 return comp.requestFocus(cause);
 882             }
 883             public boolean canBeFocusOwner(Component comp) {
 884                 return comp.canBeFocusOwner();
 885             }
 886 
 887             public boolean isVisible(Component comp) {
 888                 return comp.isVisible_NoClientCode();
 889             }
 890             public void setRequestFocusController
 891                 (RequestFocusController requestController)
 892             {
 893                  Component.setRequestFocusController(requestController);
 894             }
 895             public AppContext getAppContext(Component comp) {
 896                  return comp.appContext;
 897             }
 898             public void setAppContext(Component comp, AppContext appContext) {
 899                  comp.appContext = appContext;
 900             }
 901             public Container getParent(Component comp) {
 902                 return comp.getParent_NoClientCode();
 903             }
 904             public void setParent(Component comp, Container parent) {
 905                 comp.parent = parent;
 906             }
 907             public void setSize(Component comp, int width, int height) {
 908                 comp.width = width;
 909                 comp.height = height;
 910             }
 911             public Point getLocation(Component comp) {
 912                 return comp.location_NoClientCode();
 913             }
 914             public void setLocation(Component comp, int x, int y) {
 915                 comp.x = x;
 916                 comp.y = y;
 917             }
 918             public boolean isEnabled(Component comp) {
 919                 return comp.isEnabledImpl();
 920             }
 921             public boolean isDisplayable(Component comp) {
 922                 return comp.peer != null;
 923             }
 924             public Cursor getCursor(Component comp) {
 925                 return comp.getCursor_NoClientCode();
 926             }
 927             public ComponentPeer getPeer(Component comp) {
 928                 return comp.peer;
 929             }
 930             public void setPeer(Component comp, ComponentPeer peer) {
 931                 comp.peer = peer;
 932             }
 933             public boolean isLightweight(Component comp) {
 934                 return (comp.peer instanceof LightweightPeer);
 935             }
 936             public boolean getIgnoreRepaint(Component comp) {
 937                 return comp.ignoreRepaint;
 938             }
 939             public int getWidth(Component comp) {
 940                 return comp.width;
 941             }
 942             public int getHeight(Component comp) {
 943                 return comp.height;
 944             }
 945             public int getX(Component comp) {
 946                 return comp.x;
 947             }
 948             public int getY(Component comp) {
 949                 return comp.y;
 950             }
 951             public Color getForeground(Component comp) {
 952                 return comp.foreground;
 953             }
 954             public Color getBackground(Component comp) {
 955                 return comp.background;
 956             }
 957             public void setBackground(Component comp, Color background) {
 958                 comp.background = background;
 959             }
 960             public Font getFont(Component comp) {
 961                 return comp.getFont_NoClientCode();
 962             }
 963             public void processEvent(Component comp, AWTEvent e) {
 964                 comp.processEvent(e);
 965             }
 966 
 967             public AccessControlContext getAccessControlContext(Component comp) {
 968                 return comp.getAccessControlContext();
 969             }
 970 
 971             public void revalidateSynchronously(Component comp) {
 972                 comp.revalidateSynchronously();
 973             }
 974 
 975             @Override
 976             public void createBufferStrategy(Component comp, int numBuffers,
 977                     BufferCapabilities caps) throws AWTException {
 978                 comp.createBufferStrategy(numBuffers, caps);
 979             }
 980 
 981             @Override
 982             public BufferStrategy getBufferStrategy(Component comp) {
 983                 return comp.getBufferStrategy();
 984             }
 985         });
 986     }
 987 
 988     /**
 989      * Constructs a new component. Class <code>Component</code> can be
 990      * extended directly to create a lightweight component that does not
 991      * utilize an opaque native window. A lightweight component must be
 992      * hosted by a native container somewhere higher up in the component
 993      * tree (for example, by a <code>Frame</code> object).
 994      */
 995     protected Component() {
 996         appContext = AppContext.getAppContext();
 997     }
 998 
 999     @SuppressWarnings({"rawtypes", "unchecked"})
1000     void initializeFocusTraversalKeys() {
1001         focusTraversalKeys = new Set[3];
1002     }
1003 
1004     /**
1005      * Constructs a name for this component.  Called by <code>getName</code>
1006      * when the name is <code>null</code>.
1007      */
1008     String constructComponentName() {
1009         return null; // For strict compliance with prior platform versions, a Component
1010                      // that doesn't set its name should return null from
1011                      // getName()
1012     }
1013 
1014     /**
1015      * Gets the name of the component.
1016      * @return this component's name
1017      * @see    #setName
1018      * @since 1.1
1019      */
1020     public String getName() {
1021         if (name == null && !nameExplicitlySet) {
1022             synchronized(getObjectLock()) {
1023                 if (name == null && !nameExplicitlySet)
1024                     name = constructComponentName();
1025             }
1026         }
1027         return name;
1028     }
1029 
1030     /**
1031      * Sets the name of the component to the specified string.
1032      * @param name  the string that is to be this
1033      *           component's name
1034      * @see #getName
1035      * @since 1.1
1036      */
1037     public void setName(String name) {
1038         String oldName;
1039         synchronized(getObjectLock()) {
1040             oldName = this.name;
1041             this.name = name;
1042             nameExplicitlySet = true;
1043         }
1044         firePropertyChange("name", oldName, name);
1045     }
1046 
1047     /**
1048      * Gets the parent of this component.
1049      * @return the parent container of this component
1050      * @since 1.0
1051      */
1052     public Container getParent() {
1053         return getParent_NoClientCode();
1054     }
1055 
1056     // NOTE: This method may be called by privileged threads.
1057     //       This functionality is implemented in a package-private method
1058     //       to insure that it cannot be overridden by client subclasses.
1059     //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
1060     final Container getParent_NoClientCode() {
1061         return parent;
1062     }
1063 
1064     // This method is overridden in the Window class to return null,
1065     //    because the parent field of the Window object contains
1066     //    the owner of the window, not its parent.
1067     Container getContainer() {
1068         return getParent_NoClientCode();
1069     }
1070 
1071     /**
1072      * @deprecated As of JDK version 1.1,
1073      * programs should not directly manipulate peers;
1074      * replaced by <code>boolean isDisplayable()</code>.
1075      */
1076     @Deprecated
1077     public ComponentPeer getPeer() {
1078         return peer;
1079     }
1080 
1081     /**
1082      * Associate a <code>DropTarget</code> with this component.
1083      * The <code>Component</code> will receive drops only if it
1084      * is enabled.
1085      *
1086      * @see #isEnabled
1087      * @param dt The DropTarget
1088      */
1089 
1090     public synchronized void setDropTarget(DropTarget dt) {
1091         if (dt == dropTarget || (dropTarget != null && dropTarget.equals(dt)))
1092             return;
1093 
1094         DropTarget old;
1095 
1096         if ((old = dropTarget) != null) {
1097             if (peer != null) dropTarget.removeNotify(peer);
1098 
1099             DropTarget t = dropTarget;
1100 
1101             dropTarget = null;
1102 
1103             try {
1104                 t.setComponent(null);
1105             } catch (IllegalArgumentException iae) {
1106                 // ignore it.
1107             }
1108         }
1109 
1110         // if we have a new one, and we have a peer, add it!
1111 
1112         if ((dropTarget = dt) != null) {
1113             try {
1114                 dropTarget.setComponent(this);
1115                 if (peer != null) dropTarget.addNotify(peer);
1116             } catch (IllegalArgumentException iae) {
1117                 if (old != null) {
1118                     try {
1119                         old.setComponent(this);
1120                         if (peer != null) dropTarget.addNotify(peer);
1121                     } catch (IllegalArgumentException iae1) {
1122                         // ignore it!
1123                     }
1124                 }
1125             }
1126         }
1127     }
1128 
1129     /**
1130      * Gets the <code>DropTarget</code> associated with this
1131      * <code>Component</code>.
1132      */
1133 
1134     public synchronized DropTarget getDropTarget() { return dropTarget; }
1135 
1136     /**
1137      * Gets the <code>GraphicsConfiguration</code> associated with this
1138      * <code>Component</code>.
1139      * If the <code>Component</code> has not been assigned a specific
1140      * <code>GraphicsConfiguration</code>,
1141      * the <code>GraphicsConfiguration</code> of the
1142      * <code>Component</code> object's top-level container is
1143      * returned.
1144      * If the <code>Component</code> has been created, but not yet added
1145      * to a <code>Container</code>, this method returns <code>null</code>.
1146      *
1147      * @return the <code>GraphicsConfiguration</code> used by this
1148      *          <code>Component</code> or <code>null</code>
1149      * @since 1.3
1150      */
1151     public GraphicsConfiguration getGraphicsConfiguration() {
1152         synchronized(getTreeLock()) {
1153             return getGraphicsConfiguration_NoClientCode();
1154         }
1155     }
1156 
1157     final GraphicsConfiguration getGraphicsConfiguration_NoClientCode() {
1158         return graphicsConfig;
1159     }
1160 
1161     void setGraphicsConfiguration(GraphicsConfiguration gc) {
1162         synchronized(getTreeLock()) {
1163             if (updateGraphicsData(gc)) {
1164                 removeNotify();
1165                 addNotify();
1166             }
1167         }
1168     }
1169 
1170     boolean updateGraphicsData(GraphicsConfiguration gc) {
1171         checkTreeLock();
1172 
1173         if (graphicsConfig == gc) {
1174             return false;
1175         }
1176 
1177         graphicsConfig = gc;
1178 
1179         ComponentPeer peer = getPeer();
1180         if (peer != null) {
1181             return peer.updateGraphicsData(gc);
1182         }
1183         return false;
1184     }
1185 
1186     /**
1187      * Checks that this component's <code>GraphicsDevice</code>
1188      * <code>idString</code> matches the string argument.
1189      */
1190     void checkGD(String stringID) {
1191         if (graphicsConfig != null) {
1192             if (!graphicsConfig.getDevice().getIDstring().equals(stringID)) {
1193                 throw new IllegalArgumentException(
1194                                                    "adding a container to a container on a different GraphicsDevice");
1195             }
1196         }
1197     }
1198 
1199     /**
1200      * Gets this component's locking object (the object that owns the thread
1201      * synchronization monitor) for AWT component-tree and layout
1202      * operations.
1203      * @return this component's locking object
1204      */
1205     public final Object getTreeLock() {
1206         return LOCK;
1207     }
1208 
1209     final void checkTreeLock() {
1210         if (!Thread.holdsLock(getTreeLock())) {
1211             throw new IllegalStateException("This function should be called while holding treeLock");
1212         }
1213     }
1214 
1215     /**
1216      * Gets the toolkit of this component. Note that
1217      * the frame that contains a component controls which
1218      * toolkit is used by that component. Therefore if the component
1219      * is moved from one frame to another, the toolkit it uses may change.
1220      * @return  the toolkit of this component
1221      * @since 1.0
1222      */
1223     public Toolkit getToolkit() {
1224         return getToolkitImpl();
1225     }
1226 
1227     /*
1228      * This is called by the native code, so client code can't
1229      * be called on the toolkit thread.
1230      */
1231     final Toolkit getToolkitImpl() {
1232         Container parent = this.parent;
1233         if (parent != null) {
1234             return parent.getToolkitImpl();
1235         }
1236         return Toolkit.getDefaultToolkit();
1237     }
1238 
1239     /**
1240      * Determines whether this component is valid. A component is valid
1241      * when it is correctly sized and positioned within its parent
1242      * container and all its children are also valid.
1243      * In order to account for peers' size requirements, components are invalidated
1244      * before they are first shown on the screen. By the time the parent container
1245      * is fully realized, all its components will be valid.
1246      * @return <code>true</code> if the component is valid, <code>false</code>
1247      * otherwise
1248      * @see #validate
1249      * @see #invalidate
1250      * @since 1.0
1251      */
1252     public boolean isValid() {
1253         return (peer != null) && valid;
1254     }
1255 
1256     /**
1257      * Determines whether this component is displayable. A component is
1258      * displayable when it is connected to a native screen resource.
1259      * <p>
1260      * A component is made displayable either when it is added to
1261      * a displayable containment hierarchy or when its containment
1262      * hierarchy is made displayable.
1263      * A containment hierarchy is made displayable when its ancestor
1264      * window is either packed or made visible.
1265      * <p>
1266      * A component is made undisplayable either when it is removed from
1267      * a displayable containment hierarchy or when its containment hierarchy
1268      * is made undisplayable.  A containment hierarchy is made
1269      * undisplayable when its ancestor window is disposed.
1270      *
1271      * @return <code>true</code> if the component is displayable,
1272      * <code>false</code> otherwise
1273      * @see Container#add(Component)
1274      * @see Window#pack
1275      * @see Window#show
1276      * @see Container#remove(Component)
1277      * @see Window#dispose
1278      * @since 1.2
1279      */
1280     public boolean isDisplayable() {
1281         return getPeer() != null;
1282     }
1283 
1284     /**
1285      * Determines whether this component should be visible when its
1286      * parent is visible. Components are
1287      * initially visible, with the exception of top level components such
1288      * as <code>Frame</code> objects.
1289      * @return <code>true</code> if the component is visible,
1290      * <code>false</code> otherwise
1291      * @see #setVisible
1292      * @since 1.0
1293      */
1294     @Transient
1295     public boolean isVisible() {
1296         return isVisible_NoClientCode();
1297     }
1298     final boolean isVisible_NoClientCode() {
1299         return visible;
1300     }
1301 
1302     /**
1303      * Determines whether this component will be displayed on the screen.
1304      * @return <code>true</code> if the component and all of its ancestors
1305      *          until a toplevel window or null parent are visible,
1306      *          <code>false</code> otherwise
1307      */
1308     boolean isRecursivelyVisible() {
1309         return visible && (parent == null || parent.isRecursivelyVisible());
1310     }
1311 
1312     /**
1313      * Translates absolute coordinates into coordinates in the coordinate
1314      * space of this component.
1315      */
1316     Point pointRelativeToComponent(Point absolute) {
1317         Point compCoords = getLocationOnScreen();
1318         return new Point(absolute.x - compCoords.x,
1319                          absolute.y - compCoords.y);
1320     }
1321 
1322     /**
1323      * Assuming that mouse location is stored in PointerInfo passed
1324      * to this method, it finds a Component that is in the same
1325      * Window as this Component and is located under the mouse pointer.
1326      * If no such Component exists, null is returned.
1327      * NOTE: this method should be called under the protection of
1328      * tree lock, as it is done in Component.getMousePosition() and
1329      * Container.getMousePosition(boolean).
1330      */
1331     Component findUnderMouseInWindow(PointerInfo pi) {
1332         if (!isShowing()) {
1333             return null;
1334         }
1335         Window win = getContainingWindow();
1336         if (!Toolkit.getDefaultToolkit().getMouseInfoPeer().isWindowUnderMouse(win)) {
1337             return null;
1338         }
1339         final boolean INCLUDE_DISABLED = true;
1340         Point relativeToWindow = win.pointRelativeToComponent(pi.getLocation());
1341         Component inTheSameWindow = win.findComponentAt(relativeToWindow.x,
1342                                                         relativeToWindow.y,
1343                                                         INCLUDE_DISABLED);
1344         return inTheSameWindow;
1345     }
1346 
1347     /**
1348      * Returns the position of the mouse pointer in this <code>Component</code>'s
1349      * coordinate space if the <code>Component</code> is directly under the mouse
1350      * pointer, otherwise returns <code>null</code>.
1351      * If the <code>Component</code> is not showing on the screen, this method
1352      * returns <code>null</code> even if the mouse pointer is above the area
1353      * where the <code>Component</code> would be displayed.
1354      * If the <code>Component</code> is partially or fully obscured by other
1355      * <code>Component</code>s or native windows, this method returns a non-null
1356      * value only if the mouse pointer is located above the unobscured part of the
1357      * <code>Component</code>.
1358      * <p>
1359      * For <code>Container</code>s it returns a non-null value if the mouse is
1360      * above the <code>Container</code> itself or above any of its descendants.
1361      * Use {@link Container#getMousePosition(boolean)} if you need to exclude children.
1362      * <p>
1363      * Sometimes the exact mouse coordinates are not important, and the only thing
1364      * that matters is whether a specific <code>Component</code> is under the mouse
1365      * pointer. If the return value of this method is <code>null</code>, mouse
1366      * pointer is not directly above the <code>Component</code>.
1367      *
1368      * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true
1369      * @see       #isShowing
1370      * @see       Container#getMousePosition
1371      * @return    mouse coordinates relative to this <code>Component</code>, or null
1372      * @since     1.5
1373      */
1374     public Point getMousePosition() throws HeadlessException {
1375         if (GraphicsEnvironment.isHeadless()) {
1376             throw new HeadlessException();
1377         }
1378 
1379         PointerInfo pi = java.security.AccessController.doPrivileged(
1380                                                                      new java.security.PrivilegedAction<PointerInfo>() {
1381                                                                          public PointerInfo run() {
1382                                                                              return MouseInfo.getPointerInfo();
1383                                                                          }
1384                                                                      }
1385                                                                      );
1386 
1387         synchronized (getTreeLock()) {
1388             Component inTheSameWindow = findUnderMouseInWindow(pi);
1389             if (!isSameOrAncestorOf(inTheSameWindow, true)) {
1390                 return null;
1391             }
1392             return pointRelativeToComponent(pi.getLocation());
1393         }
1394     }
1395 
1396     /**
1397      * Overridden in Container. Must be called under TreeLock.
1398      */
1399     boolean isSameOrAncestorOf(Component comp, boolean allowChildren) {
1400         return comp == this;
1401     }
1402 
1403     /**
1404      * Determines whether this component is showing on screen. This means
1405      * that the component must be visible, and it must be in a container
1406      * that is visible and showing.
1407      * <p>
1408      * <strong>Note:</strong> sometimes there is no way to detect whether the
1409      * {@code Component} is actually visible to the user.  This can happen when:
1410      * <ul>
1411      * <li>the component has been added to a visible {@code ScrollPane} but
1412      * the {@code Component} is not currently in the scroll pane's view port.
1413      * <li>the {@code Component} is obscured by another {@code Component} or
1414      * {@code Container}.
1415      * </ul>
1416      * @return <code>true</code> if the component is showing,
1417      *          <code>false</code> otherwise
1418      * @see #setVisible
1419      * @since 1.0
1420      */
1421     public boolean isShowing() {
1422         if (visible && (peer != null)) {
1423             Container parent = this.parent;
1424             return (parent == null) || parent.isShowing();
1425         }
1426         return false;
1427     }
1428 
1429     /**
1430      * Determines whether this component is enabled. An enabled component
1431      * can respond to user input and generate events. Components are
1432      * enabled initially by default. A component may be enabled or disabled by
1433      * calling its <code>setEnabled</code> method.
1434      * @return <code>true</code> if the component is enabled,
1435      *          <code>false</code> otherwise
1436      * @see #setEnabled
1437      * @since 1.0
1438      */
1439     public boolean isEnabled() {
1440         return isEnabledImpl();
1441     }
1442 
1443     /*
1444      * This is called by the native code, so client code can't
1445      * be called on the toolkit thread.
1446      */
1447     final boolean isEnabledImpl() {
1448         return enabled;
1449     }
1450 
1451     /**
1452      * Enables or disables this component, depending on the value of the
1453      * parameter <code>b</code>. An enabled component can respond to user
1454      * input and generate events. Components are enabled initially by default.
1455      *
1456      * <p>Note: Disabling a lightweight component does not prevent it from
1457      * receiving MouseEvents.
1458      * <p>Note: Disabling a heavyweight container prevents all components
1459      * in this container from receiving any input events.  But disabling a
1460      * lightweight container affects only this container.
1461      *
1462      * @param     b   If <code>true</code>, this component is
1463      *            enabled; otherwise this component is disabled
1464      * @see #isEnabled
1465      * @see #isLightweight
1466      * @since 1.1
1467      */
1468     public void setEnabled(boolean b) {
1469         enable(b);
1470     }
1471 
1472     /**
1473      * @deprecated As of JDK version 1.1,
1474      * replaced by <code>setEnabled(boolean)</code>.
1475      */
1476     @Deprecated
1477     public void enable() {
1478         if (!enabled) {
1479             synchronized (getTreeLock()) {
1480                 enabled = true;
1481                 ComponentPeer peer = this.peer;
1482                 if (peer != null) {
1483                     peer.setEnabled(true);
1484                     if (visible) {
1485                         updateCursorImmediately();
1486                     }
1487                 }
1488             }
1489             if (accessibleContext != null) {
1490                 accessibleContext.firePropertyChange(
1491                                                      AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
1492                                                      null, AccessibleState.ENABLED);
1493             }
1494         }
1495     }
1496 
1497     /**
1498      * @deprecated As of JDK version 1.1,
1499      * replaced by <code>setEnabled(boolean)</code>.
1500      */
1501     @Deprecated
1502     public void enable(boolean b) {
1503         if (b) {
1504             enable();
1505         } else {
1506             disable();
1507         }
1508     }
1509 
1510     /**
1511      * @deprecated As of JDK version 1.1,
1512      * replaced by <code>setEnabled(boolean)</code>.
1513      */
1514     @Deprecated
1515     public void disable() {
1516         if (enabled) {
1517             KeyboardFocusManager.clearMostRecentFocusOwner(this);
1518             synchronized (getTreeLock()) {
1519                 enabled = false;
1520                 // A disabled lw container is allowed to contain a focus owner.
1521                 if ((isFocusOwner() || (containsFocus() && !isLightweight())) &&
1522                     KeyboardFocusManager.isAutoFocusTransferEnabled())
1523                 {
1524                     // Don't clear the global focus owner. If transferFocus
1525                     // fails, we want the focus to stay on the disabled
1526                     // Component so that keyboard traversal, et. al. still
1527                     // makes sense to the user.
1528                     transferFocus(false);
1529                 }
1530                 ComponentPeer peer = this.peer;
1531                 if (peer != null) {
1532                     peer.setEnabled(false);
1533                     if (visible) {
1534                         updateCursorImmediately();
1535                     }
1536                 }
1537             }
1538             if (accessibleContext != null) {
1539                 accessibleContext.firePropertyChange(
1540                                                      AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
1541                                                      null, AccessibleState.ENABLED);
1542             }
1543         }
1544     }
1545 
1546     /**
1547      * Returns true if this component is painted to an offscreen image
1548      * ("buffer") that's copied to the screen later.  Component
1549      * subclasses that support double buffering should override this
1550      * method to return true if double buffering is enabled.
1551      *
1552      * @return false by default
1553      */
1554     public boolean isDoubleBuffered() {
1555         return false;
1556     }
1557 
1558     /**
1559      * Enables or disables input method support for this component. If input
1560      * method support is enabled and the component also processes key events,
1561      * incoming events are offered to
1562      * the current input method and will only be processed by the component or
1563      * dispatched to its listeners if the input method does not consume them.
1564      * By default, input method support is enabled.
1565      *
1566      * @param enable true to enable, false to disable
1567      * @see #processKeyEvent
1568      * @since 1.2
1569      */
1570     public void enableInputMethods(boolean enable) {
1571         if (enable) {
1572             if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0)
1573                 return;
1574 
1575             // If this component already has focus, then activate the
1576             // input method by dispatching a synthesized focus gained
1577             // event.
1578             if (isFocusOwner()) {
1579                 InputContext inputContext = getInputContext();
1580                 if (inputContext != null) {
1581                     FocusEvent focusGainedEvent =
1582                         new FocusEvent(this, FocusEvent.FOCUS_GAINED);
1583                     inputContext.dispatchEvent(focusGainedEvent);
1584                 }
1585             }
1586 
1587             eventMask |= AWTEvent.INPUT_METHODS_ENABLED_MASK;
1588         } else {
1589             if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) {
1590                 InputContext inputContext = getInputContext();
1591                 if (inputContext != null) {
1592                     inputContext.endComposition();
1593                     inputContext.removeNotify(this);
1594                 }
1595             }
1596             eventMask &= ~AWTEvent.INPUT_METHODS_ENABLED_MASK;
1597         }
1598     }
1599 
1600     /**
1601      * Shows or hides this component depending on the value of parameter
1602      * <code>b</code>.
1603      * <p>
1604      * This method changes layout-related information, and therefore,
1605      * invalidates the component hierarchy.
1606      *
1607      * @param b  if <code>true</code>, shows this component;
1608      * otherwise, hides this component
1609      * @see #isVisible
1610      * @see #invalidate
1611      * @since 1.1
1612      */
1613     public void setVisible(boolean b) {
1614         show(b);
1615     }
1616 
1617     /**
1618      * @deprecated As of JDK version 1.1,
1619      * replaced by <code>setVisible(boolean)</code>.
1620      */
1621     @Deprecated
1622     public void show() {
1623         if (!visible) {
1624             synchronized (getTreeLock()) {
1625                 visible = true;
1626                 mixOnShowing();
1627                 ComponentPeer peer = this.peer;
1628                 if (peer != null) {
1629                     peer.setVisible(true);
1630                     createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,
1631                                           this, parent,
1632                                           HierarchyEvent.SHOWING_CHANGED,
1633                                           Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
1634                     if (peer instanceof LightweightPeer) {
1635                         repaint();
1636                     }
1637                     updateCursorImmediately();
1638                 }
1639 
1640                 if (componentListener != null ||
1641                     (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||
1642                     Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) {
1643                     ComponentEvent e = new ComponentEvent(this,
1644                                                           ComponentEvent.COMPONENT_SHOWN);
1645                     Toolkit.getEventQueue().postEvent(e);
1646                 }
1647             }
1648             Container parent = this.parent;
1649             if (parent != null) {
1650                 parent.invalidate();
1651             }
1652         }
1653     }
1654 
1655     /**
1656      * @deprecated As of JDK version 1.1,
1657      * replaced by <code>setVisible(boolean)</code>.
1658      */
1659     @Deprecated
1660     public void show(boolean b) {
1661         if (b) {
1662             show();
1663         } else {
1664             hide();
1665         }
1666     }
1667 
1668     boolean containsFocus() {
1669         return isFocusOwner();
1670     }
1671 
1672     void clearMostRecentFocusOwnerOnHide() {
1673         KeyboardFocusManager.clearMostRecentFocusOwner(this);
1674     }
1675 
1676     void clearCurrentFocusCycleRootOnHide() {
1677         /* do nothing */
1678     }
1679 
1680     /*
1681      * Delete references from LightweithDispatcher of a heavyweight parent
1682      */
1683     void clearLightweightDispatcherOnRemove(Component removedComponent) {
1684         if (parent != null) {
1685             parent.clearLightweightDispatcherOnRemove(removedComponent);
1686         }
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 1.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 1.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 1.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 1.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 1.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 1.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  1.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 1.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 1.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 1.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 1.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 1.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 1.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 1.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 1.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 1.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     1.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     1.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     1.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     1.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     1.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     1.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      1.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     1.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     1.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     1.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     1.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 1.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     1.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     1.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     1.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     1.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   1.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     1.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     1.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     1.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     1.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    1.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    1.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     1.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     1.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     1.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     1.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           default:
4867               break;
4868         }
4869 
4870         /*
4871          * 6. Deliver event for normal processing
4872          */
4873         if (newEventsOnly) {
4874             // Filtering needs to really be moved to happen at a lower
4875             // level in order to get maximum performance gain;  it is
4876             // here temporarily to ensure the API spec is honored.
4877             //
4878             if (eventEnabled(e)) {
4879                 processEvent(e);
4880             }
4881         } else if (id == MouseEvent.MOUSE_WHEEL) {
4882             // newEventsOnly will be false for a listenerless ScrollPane, but
4883             // MouseWheelEvents still need to be dispatched to it so scrolling
4884             // can be done.
4885             autoProcessMouseWheel((MouseWheelEvent)e);
4886         } else if (!(e instanceof MouseEvent && !postsOldMouseEvents())) {
4887             //
4888             // backward compatibility
4889             //
4890             Event olde = e.convertToOld();
4891             if (olde != null) {
4892                 int key = olde.key;
4893                 int modifiers = olde.modifiers;
4894 
4895                 postEvent(olde);
4896                 if (olde.isConsumed()) {
4897                     e.consume();
4898                 }
4899                 // if target changed key or modifier values, copy them
4900                 // back to original event
4901                 //
4902                 switch(olde.id) {
4903                   case Event.KEY_PRESS:
4904                   case Event.KEY_RELEASE:
4905                   case Event.KEY_ACTION:
4906                   case Event.KEY_ACTION_RELEASE:
4907                       if (olde.key != key) {
4908                           ((KeyEvent)e).setKeyChar(olde.getKeyEventChar());
4909                       }
4910                       if (olde.modifiers != modifiers) {
4911                           ((KeyEvent)e).setModifiers(olde.modifiers);
4912                       }
4913                       break;
4914                   default:
4915                       break;
4916                 }
4917             }
4918         }
4919 
4920         /*
4921          * 9. Allow the peer to process the event.
4922          * Except KeyEvents, they will be processed by peer after
4923          * all KeyEventPostProcessors
4924          * (see DefaultKeyboardFocusManager.dispatchKeyEvent())
4925          */
4926         if (!(e instanceof KeyEvent)) {
4927             ComponentPeer tpeer = peer;
4928             if (e instanceof FocusEvent && (tpeer == null || tpeer instanceof LightweightPeer)) {
4929                 // if focus owner is lightweight then its native container
4930                 // processes event
4931                 Component source = (Component)e.getSource();
4932                 if (source != null) {
4933                     Container target = source.getNativeContainer();
4934                     if (target != null) {
4935                         tpeer = target.getPeer();
4936                     }
4937                 }
4938             }
4939             if (tpeer != null) {
4940                 tpeer.handleEvent(e);
4941             }
4942         }
4943     } // dispatchEventImpl()
4944 
4945     /*
4946      * If newEventsOnly is false, method is called so that ScrollPane can
4947      * override it and handle common-case mouse wheel scrolling.  NOP
4948      * for Component.
4949      */
4950     void autoProcessMouseWheel(MouseWheelEvent e) {}
4951 
4952     /*
4953      * Dispatch given MouseWheelEvent to the first ancestor for which
4954      * MouseWheelEvents are enabled.
4955      *
4956      * Returns whether or not event was dispatched to an ancestor
4957      */
4958     boolean dispatchMouseWheelToAncestor(MouseWheelEvent e) {
4959         int newX, newY;
4960         newX = e.getX() + getX(); // Coordinates take into account at least
4961         newY = e.getY() + getY(); // the cursor's position relative to this
4962                                   // Component (e.getX()), and this Component's
4963                                   // position relative to its parent.
4964         MouseWheelEvent newMWE;
4965 
4966         if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
4967             eventLog.finest("dispatchMouseWheelToAncestor");
4968             eventLog.finest("orig event src is of " + e.getSource().getClass());
4969         }
4970 
4971         /* parent field for Window refers to the owning Window.
4972          * MouseWheelEvents should NOT be propagated into owning Windows
4973          */
4974         synchronized (getTreeLock()) {
4975             Container anc = getParent();
4976             while (anc != null && !anc.eventEnabled(e)) {
4977                 // fix coordinates to be relative to new event source
4978                 newX += anc.getX();
4979                 newY += anc.getY();
4980 
4981                 if (!(anc instanceof Window)) {
4982                     anc = anc.getParent();
4983                 }
4984                 else {
4985                     break;
4986                 }
4987             }
4988 
4989             if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
4990                 eventLog.finest("new event src is " + anc.getClass());
4991             }
4992 
4993             if (anc != null && anc.eventEnabled(e)) {
4994                 // Change event to be from new source, with new x,y
4995                 // For now, just create a new event - yucky
4996 
4997                 newMWE = new MouseWheelEvent(anc, // new source
4998                                              e.getID(),
4999                                              e.getWhen(),
5000                                              e.getModifiers(),
5001                                              newX, // x relative to new source
5002                                              newY, // y relative to new source
5003                                              e.getXOnScreen(),
5004                                              e.getYOnScreen(),
5005                                              e.getClickCount(),
5006                                              e.isPopupTrigger(),
5007                                              e.getScrollType(),
5008                                              e.getScrollAmount(),
5009                                              e.getWheelRotation(),
5010                                              e.getPreciseWheelRotation());
5011                 ((AWTEvent)e).copyPrivateDataInto(newMWE);
5012                 // When dispatching a wheel event to
5013                 // ancestor, there is no need trying to find descendant
5014                 // lightweights to dispatch event to.
5015                 // If we dispatch the event to toplevel ancestor,
5016                 // this could encolse the loop: 6480024.
5017                 anc.dispatchEventToSelf(newMWE);
5018                 if (newMWE.isConsumed()) {
5019                     e.consume();
5020                 }
5021                 return true;
5022             }
5023         }
5024         return false;
5025     }
5026 
5027     boolean areInputMethodsEnabled() {
5028         // in 1.2, we assume input method support is required for all
5029         // components that handle key events, but components can turn off
5030         // input methods by calling enableInputMethods(false).
5031         return ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) &&
5032             ((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 || keyListener != null);
5033     }
5034 
5035     // REMIND: remove when filtering is handled at lower level
5036     boolean eventEnabled(AWTEvent e) {
5037         return eventTypeEnabled(e.id);
5038     }
5039 
5040     boolean eventTypeEnabled(int type) {
5041         switch(type) {
5042           case ComponentEvent.COMPONENT_MOVED:
5043           case ComponentEvent.COMPONENT_RESIZED:
5044           case ComponentEvent.COMPONENT_SHOWN:
5045           case ComponentEvent.COMPONENT_HIDDEN:
5046               if ((eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||
5047                   componentListener != null) {
5048                   return true;
5049               }
5050               break;
5051           case FocusEvent.FOCUS_GAINED:
5052           case FocusEvent.FOCUS_LOST:
5053               if ((eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0 ||
5054                   focusListener != null) {
5055                   return true;
5056               }
5057               break;
5058           case KeyEvent.KEY_PRESSED:
5059           case KeyEvent.KEY_RELEASED:
5060           case KeyEvent.KEY_TYPED:
5061               if ((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 ||
5062                   keyListener != null) {
5063                   return true;
5064               }
5065               break;
5066           case MouseEvent.MOUSE_PRESSED:
5067           case MouseEvent.MOUSE_RELEASED:
5068           case MouseEvent.MOUSE_ENTERED:
5069           case MouseEvent.MOUSE_EXITED:
5070           case MouseEvent.MOUSE_CLICKED:
5071               if ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0 ||
5072                   mouseListener != null) {
5073                   return true;
5074               }
5075               break;
5076           case MouseEvent.MOUSE_MOVED:
5077           case MouseEvent.MOUSE_DRAGGED:
5078               if ((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0 ||
5079                   mouseMotionListener != null) {
5080                   return true;
5081               }
5082               break;
5083           case MouseEvent.MOUSE_WHEEL:
5084               if ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0 ||
5085                   mouseWheelListener != null) {
5086                   return true;
5087               }
5088               break;
5089           case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED:
5090           case InputMethodEvent.CARET_POSITION_CHANGED:
5091               if ((eventMask & AWTEvent.INPUT_METHOD_EVENT_MASK) != 0 ||
5092                   inputMethodListener != null) {
5093                   return true;
5094               }
5095               break;
5096           case HierarchyEvent.HIERARCHY_CHANGED:
5097               if ((eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
5098                   hierarchyListener != null) {
5099                   return true;
5100               }
5101               break;
5102           case HierarchyEvent.ANCESTOR_MOVED:
5103           case HierarchyEvent.ANCESTOR_RESIZED:
5104               if ((eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 ||
5105                   hierarchyBoundsListener != null) {
5106                   return true;
5107               }
5108               break;
5109           case ActionEvent.ACTION_PERFORMED:
5110               if ((eventMask & AWTEvent.ACTION_EVENT_MASK) != 0) {
5111                   return true;
5112               }
5113               break;
5114           case TextEvent.TEXT_VALUE_CHANGED:
5115               if ((eventMask & AWTEvent.TEXT_EVENT_MASK) != 0) {
5116                   return true;
5117               }
5118               break;
5119           case ItemEvent.ITEM_STATE_CHANGED:
5120               if ((eventMask & AWTEvent.ITEM_EVENT_MASK) != 0) {
5121                   return true;
5122               }
5123               break;
5124           case AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED:
5125               if ((eventMask & AWTEvent.ADJUSTMENT_EVENT_MASK) != 0) {
5126                   return true;
5127               }
5128               break;
5129           default:
5130               break;
5131         }
5132         //
5133         // Always pass on events defined by external programs.
5134         //
5135         if (type > AWTEvent.RESERVED_ID_MAX) {
5136             return true;
5137         }
5138         return false;
5139     }
5140 
5141     /**
5142      * @deprecated As of JDK version 1.1,
5143      * replaced by dispatchEvent(AWTEvent).
5144      */
5145     @Deprecated
5146     public boolean postEvent(Event e) {
5147         ComponentPeer peer = this.peer;
5148 
5149         if (handleEvent(e)) {
5150             e.consume();
5151             return true;
5152         }
5153 
5154         Component parent = this.parent;
5155         int eventx = e.x;
5156         int eventy = e.y;
5157         if (parent != null) {
5158             e.translate(x, y);
5159             if (parent.postEvent(e)) {
5160                 e.consume();
5161                 return true;
5162             }
5163             // restore coords
5164             e.x = eventx;
5165             e.y = eventy;
5166         }
5167         return false;
5168     }
5169 
5170     // Event source interfaces
5171 
5172     /**
5173      * Adds the specified component listener to receive component events from
5174      * this component.
5175      * If listener <code>l</code> is <code>null</code>,
5176      * no exception is thrown and no action is performed.
5177      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5178      * >AWT Threading Issues</a> for details on AWT's threading model.
5179      *
5180      * @param    l   the component listener
5181      * @see      java.awt.event.ComponentEvent
5182      * @see      java.awt.event.ComponentListener
5183      * @see      #removeComponentListener
5184      * @see      #getComponentListeners
5185      * @since    1.1
5186      */
5187     public synchronized void addComponentListener(ComponentListener l) {
5188         if (l == null) {
5189             return;
5190         }
5191         componentListener = AWTEventMulticaster.add(componentListener, l);
5192         newEventsOnly = true;
5193     }
5194 
5195     /**
5196      * Removes the specified component listener so that it no longer
5197      * receives component events from this component. This method performs
5198      * no function, nor does it throw an exception, if the listener
5199      * specified by the argument was not previously added to this component.
5200      * If listener <code>l</code> is <code>null</code>,
5201      * no exception is thrown and no action is performed.
5202      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5203      * >AWT Threading Issues</a> for details on AWT's threading model.
5204      * @param    l   the component listener
5205      * @see      java.awt.event.ComponentEvent
5206      * @see      java.awt.event.ComponentListener
5207      * @see      #addComponentListener
5208      * @see      #getComponentListeners
5209      * @since    1.1
5210      */
5211     public synchronized void removeComponentListener(ComponentListener l) {
5212         if (l == null) {
5213             return;
5214         }
5215         componentListener = AWTEventMulticaster.remove(componentListener, l);
5216     }
5217 
5218     /**
5219      * Returns an array of all the component listeners
5220      * registered on this component.
5221      *
5222      * @return all <code>ComponentListener</code>s of this component
5223      *         or an empty array if no component
5224      *         listeners are currently registered
5225      *
5226      * @see #addComponentListener
5227      * @see #removeComponentListener
5228      * @since 1.4
5229      */
5230     public synchronized ComponentListener[] getComponentListeners() {
5231         return getListeners(ComponentListener.class);
5232     }
5233 
5234     /**
5235      * Adds the specified focus listener to receive focus events from
5236      * this component when this component gains input focus.
5237      * If listener <code>l</code> is <code>null</code>,
5238      * no exception is thrown and no action is performed.
5239      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5240      * >AWT Threading Issues</a> for details on AWT's threading model.
5241      *
5242      * @param    l   the focus listener
5243      * @see      java.awt.event.FocusEvent
5244      * @see      java.awt.event.FocusListener
5245      * @see      #removeFocusListener
5246      * @see      #getFocusListeners
5247      * @since    1.1
5248      */
5249     public synchronized void addFocusListener(FocusListener l) {
5250         if (l == null) {
5251             return;
5252         }
5253         focusListener = AWTEventMulticaster.add(focusListener, l);
5254         newEventsOnly = true;
5255 
5256         // if this is a lightweight component, enable focus events
5257         // in the native container.
5258         if (peer instanceof LightweightPeer) {
5259             parent.proxyEnableEvents(AWTEvent.FOCUS_EVENT_MASK);
5260         }
5261     }
5262 
5263     /**
5264      * Removes the specified focus listener so that it no longer
5265      * receives focus events from this component. This method performs
5266      * no function, nor does it throw an exception, if the listener
5267      * specified by the argument was not previously added to this component.
5268      * If listener <code>l</code> is <code>null</code>,
5269      * no exception is thrown and no action is performed.
5270      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5271      * >AWT Threading Issues</a> for details on AWT's threading model.
5272      *
5273      * @param    l   the focus listener
5274      * @see      java.awt.event.FocusEvent
5275      * @see      java.awt.event.FocusListener
5276      * @see      #addFocusListener
5277      * @see      #getFocusListeners
5278      * @since    1.1
5279      */
5280     public synchronized void removeFocusListener(FocusListener l) {
5281         if (l == null) {
5282             return;
5283         }
5284         focusListener = AWTEventMulticaster.remove(focusListener, l);
5285     }
5286 
5287     /**
5288      * Returns an array of all the focus listeners
5289      * registered on this component.
5290      *
5291      * @return all of this component's <code>FocusListener</code>s
5292      *         or an empty array if no component
5293      *         listeners are currently registered
5294      *
5295      * @see #addFocusListener
5296      * @see #removeFocusListener
5297      * @since 1.4
5298      */
5299     public synchronized FocusListener[] getFocusListeners() {
5300         return getListeners(FocusListener.class);
5301     }
5302 
5303     /**
5304      * Adds the specified hierarchy listener to receive hierarchy changed
5305      * events from this component when the hierarchy to which this container
5306      * belongs changes.
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 hierarchy listener
5313      * @see      java.awt.event.HierarchyEvent
5314      * @see      java.awt.event.HierarchyListener
5315      * @see      #removeHierarchyListener
5316      * @see      #getHierarchyListeners
5317      * @since    1.3
5318      */
5319     public void addHierarchyListener(HierarchyListener l) {
5320         if (l == null) {
5321             return;
5322         }
5323         boolean notifyAncestors;
5324         synchronized (this) {
5325             notifyAncestors =
5326                 (hierarchyListener == null &&
5327                  (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0);
5328             hierarchyListener = AWTEventMulticaster.add(hierarchyListener, l);
5329             notifyAncestors = (notifyAncestors && hierarchyListener != null);
5330             newEventsOnly = true;
5331         }
5332         if (notifyAncestors) {
5333             synchronized (getTreeLock()) {
5334                 adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK,
5335                                                 1);
5336             }
5337         }
5338     }
5339 
5340     /**
5341      * Removes the specified hierarchy listener so that it no longer
5342      * receives hierarchy changed events from this component. This method
5343      * performs no function, nor does it throw an exception, if the listener
5344      * specified by the argument was not previously added to this component.
5345      * If listener <code>l</code> is <code>null</code>,
5346      * no exception is thrown and no action is performed.
5347      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5348      * >AWT Threading Issues</a> for details on AWT's threading model.
5349      *
5350      * @param    l   the hierarchy listener
5351      * @see      java.awt.event.HierarchyEvent
5352      * @see      java.awt.event.HierarchyListener
5353      * @see      #addHierarchyListener
5354      * @see      #getHierarchyListeners
5355      * @since    1.3
5356      */
5357     public void removeHierarchyListener(HierarchyListener l) {
5358         if (l == null) {
5359             return;
5360         }
5361         boolean notifyAncestors;
5362         synchronized (this) {
5363             notifyAncestors =
5364                 (hierarchyListener != null &&
5365                  (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0);
5366             hierarchyListener =
5367                 AWTEventMulticaster.remove(hierarchyListener, l);
5368             notifyAncestors = (notifyAncestors && hierarchyListener == null);
5369         }
5370         if (notifyAncestors) {
5371             synchronized (getTreeLock()) {
5372                 adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK,
5373                                                 -1);
5374             }
5375         }
5376     }
5377 
5378     /**
5379      * Returns an array of all the hierarchy listeners
5380      * registered on this component.
5381      *
5382      * @return all of this component's <code>HierarchyListener</code>s
5383      *         or an empty array if no hierarchy
5384      *         listeners are currently registered
5385      *
5386      * @see      #addHierarchyListener
5387      * @see      #removeHierarchyListener
5388      * @since    1.4
5389      */
5390     public synchronized HierarchyListener[] getHierarchyListeners() {
5391         return getListeners(HierarchyListener.class);
5392     }
5393 
5394     /**
5395      * Adds the specified hierarchy bounds listener to receive hierarchy
5396      * bounds events from this component when the hierarchy to which this
5397      * container belongs changes.
5398      * If listener <code>l</code> is <code>null</code>,
5399      * no exception is thrown and no action is performed.
5400      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5401      * >AWT Threading Issues</a> for details on AWT's threading model.
5402      *
5403      * @param    l   the hierarchy bounds listener
5404      * @see      java.awt.event.HierarchyEvent
5405      * @see      java.awt.event.HierarchyBoundsListener
5406      * @see      #removeHierarchyBoundsListener
5407      * @see      #getHierarchyBoundsListeners
5408      * @since    1.3
5409      */
5410     public void addHierarchyBoundsListener(HierarchyBoundsListener l) {
5411         if (l == null) {
5412             return;
5413         }
5414         boolean notifyAncestors;
5415         synchronized (this) {
5416             notifyAncestors =
5417                 (hierarchyBoundsListener == null &&
5418                  (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0);
5419             hierarchyBoundsListener =
5420                 AWTEventMulticaster.add(hierarchyBoundsListener, l);
5421             notifyAncestors = (notifyAncestors &&
5422                                hierarchyBoundsListener != null);
5423             newEventsOnly = true;
5424         }
5425         if (notifyAncestors) {
5426             synchronized (getTreeLock()) {
5427                 adjustListeningChildrenOnParent(
5428                                                 AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, 1);
5429             }
5430         }
5431     }
5432 
5433     /**
5434      * Removes the specified hierarchy bounds listener so that it no longer
5435      * receives hierarchy bounds events from this component. This method
5436      * performs no function, nor does it throw an exception, if the listener
5437      * specified by the argument was not previously added to this component.
5438      * If listener <code>l</code> is <code>null</code>,
5439      * no exception is thrown and no action is performed.
5440      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5441      * >AWT Threading Issues</a> for details on AWT's threading model.
5442      *
5443      * @param    l   the hierarchy bounds listener
5444      * @see      java.awt.event.HierarchyEvent
5445      * @see      java.awt.event.HierarchyBoundsListener
5446      * @see      #addHierarchyBoundsListener
5447      * @see      #getHierarchyBoundsListeners
5448      * @since    1.3
5449      */
5450     public void removeHierarchyBoundsListener(HierarchyBoundsListener l) {
5451         if (l == null) {
5452             return;
5453         }
5454         boolean notifyAncestors;
5455         synchronized (this) {
5456             notifyAncestors =
5457                 (hierarchyBoundsListener != null &&
5458                  (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0);
5459             hierarchyBoundsListener =
5460                 AWTEventMulticaster.remove(hierarchyBoundsListener, l);
5461             notifyAncestors = (notifyAncestors &&
5462                                hierarchyBoundsListener == null);
5463         }
5464         if (notifyAncestors) {
5465             synchronized (getTreeLock()) {
5466                 adjustListeningChildrenOnParent(
5467                                                 AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, -1);
5468             }
5469         }
5470     }
5471 
5472     // Should only be called while holding the tree lock
5473     int numListening(long mask) {
5474         // One mask or the other, but not neither or both.
5475         if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
5476             if ((mask != AWTEvent.HIERARCHY_EVENT_MASK) &&
5477                 (mask != AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK))
5478             {
5479                 eventLog.fine("Assertion failed");
5480             }
5481         }
5482         if ((mask == AWTEvent.HIERARCHY_EVENT_MASK &&
5483              (hierarchyListener != null ||
5484               (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0)) ||
5485             (mask == AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK &&
5486              (hierarchyBoundsListener != null ||
5487               (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0))) {
5488             return 1;
5489         } else {
5490             return 0;
5491         }
5492     }
5493 
5494     // Should only be called while holding tree lock
5495     int countHierarchyMembers() {
5496         return 1;
5497     }
5498     // Should only be called while holding the tree lock
5499     int createHierarchyEvents(int id, Component changed,
5500                               Container changedParent, long changeFlags,
5501                               boolean enabledOnToolkit) {
5502         switch (id) {
5503           case HierarchyEvent.HIERARCHY_CHANGED:
5504               if (hierarchyListener != null ||
5505                   (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
5506                   enabledOnToolkit) {
5507                   HierarchyEvent e = new HierarchyEvent(this, id, changed,
5508                                                         changedParent,
5509                                                         changeFlags);
5510                   dispatchEvent(e);
5511                   return 1;
5512               }
5513               break;
5514           case HierarchyEvent.ANCESTOR_MOVED:
5515           case HierarchyEvent.ANCESTOR_RESIZED:
5516               if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
5517                   if (changeFlags != 0) {
5518                       eventLog.fine("Assertion (changeFlags == 0) failed");
5519                   }
5520               }
5521               if (hierarchyBoundsListener != null ||
5522                   (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 ||
5523                   enabledOnToolkit) {
5524                   HierarchyEvent e = new HierarchyEvent(this, id, changed,
5525                                                         changedParent);
5526                   dispatchEvent(e);
5527                   return 1;
5528               }
5529               break;
5530           default:
5531               // assert false
5532               if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
5533                   eventLog.fine("This code must never be reached");
5534               }
5535               break;
5536         }
5537         return 0;
5538     }
5539 
5540     /**
5541      * Returns an array of all the hierarchy bounds listeners
5542      * registered on this component.
5543      *
5544      * @return all of this component's <code>HierarchyBoundsListener</code>s
5545      *         or an empty array if no hierarchy bounds
5546      *         listeners are currently registered
5547      *
5548      * @see      #addHierarchyBoundsListener
5549      * @see      #removeHierarchyBoundsListener
5550      * @since    1.4
5551      */
5552     public synchronized HierarchyBoundsListener[] getHierarchyBoundsListeners() {
5553         return getListeners(HierarchyBoundsListener.class);
5554     }
5555 
5556     /*
5557      * Should only be called while holding the tree lock.
5558      * It's added only for overriding in java.awt.Window
5559      * because parent in Window is owner.
5560      */
5561     void adjustListeningChildrenOnParent(long mask, int num) {
5562         if (parent != null) {
5563             parent.adjustListeningChildren(mask, num);
5564         }
5565     }
5566 
5567     /**
5568      * Adds the specified key listener to receive key events from
5569      * this component.
5570      * If l is null, no exception is thrown and no action is performed.
5571      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5572      * >AWT Threading Issues</a> for details on AWT's threading model.
5573      *
5574      * @param    l   the key listener.
5575      * @see      java.awt.event.KeyEvent
5576      * @see      java.awt.event.KeyListener
5577      * @see      #removeKeyListener
5578      * @see      #getKeyListeners
5579      * @since    1.1
5580      */
5581     public synchronized void addKeyListener(KeyListener l) {
5582         if (l == null) {
5583             return;
5584         }
5585         keyListener = AWTEventMulticaster.add(keyListener, l);
5586         newEventsOnly = true;
5587 
5588         // if this is a lightweight component, enable key events
5589         // in the native container.
5590         if (peer instanceof LightweightPeer) {
5591             parent.proxyEnableEvents(AWTEvent.KEY_EVENT_MASK);
5592         }
5593     }
5594 
5595     /**
5596      * Removes the specified key listener so that it no longer
5597      * receives key events from this component. This method performs
5598      * no function, nor does it throw an exception, if the listener
5599      * specified by the argument was not previously added to this component.
5600      * If listener <code>l</code> is <code>null</code>,
5601      * no exception is thrown and no action is performed.
5602      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5603      * >AWT Threading Issues</a> for details on AWT's threading model.
5604      *
5605      * @param    l   the key listener
5606      * @see      java.awt.event.KeyEvent
5607      * @see      java.awt.event.KeyListener
5608      * @see      #addKeyListener
5609      * @see      #getKeyListeners
5610      * @since    1.1
5611      */
5612     public synchronized void removeKeyListener(KeyListener l) {
5613         if (l == null) {
5614             return;
5615         }
5616         keyListener = AWTEventMulticaster.remove(keyListener, l);
5617     }
5618 
5619     /**
5620      * Returns an array of all the key listeners
5621      * registered on this component.
5622      *
5623      * @return all of this component's <code>KeyListener</code>s
5624      *         or an empty array if no key
5625      *         listeners are currently registered
5626      *
5627      * @see      #addKeyListener
5628      * @see      #removeKeyListener
5629      * @since    1.4
5630      */
5631     public synchronized KeyListener[] getKeyListeners() {
5632         return getListeners(KeyListener.class);
5633     }
5634 
5635     /**
5636      * Adds the specified mouse listener to receive mouse events from
5637      * this component.
5638      * If listener <code>l</code> is <code>null</code>,
5639      * no exception is thrown and no action is performed.
5640      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5641      * >AWT Threading Issues</a> for details on AWT's threading model.
5642      *
5643      * @param    l   the mouse listener
5644      * @see      java.awt.event.MouseEvent
5645      * @see      java.awt.event.MouseListener
5646      * @see      #removeMouseListener
5647      * @see      #getMouseListeners
5648      * @since    1.1
5649      */
5650     public synchronized void addMouseListener(MouseListener l) {
5651         if (l == null) {
5652             return;
5653         }
5654         mouseListener = AWTEventMulticaster.add(mouseListener,l);
5655         newEventsOnly = true;
5656 
5657         // if this is a lightweight component, enable mouse events
5658         // in the native container.
5659         if (peer instanceof LightweightPeer) {
5660             parent.proxyEnableEvents(AWTEvent.MOUSE_EVENT_MASK);
5661         }
5662     }
5663 
5664     /**
5665      * Removes the specified mouse listener so that it no longer
5666      * receives mouse events from this component. This method performs
5667      * no function, nor does it throw an exception, if the listener
5668      * specified by the argument was not previously added to this component.
5669      * If listener <code>l</code> is <code>null</code>,
5670      * no exception is thrown and no action is performed.
5671      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5672      * >AWT Threading Issues</a> for details on AWT's threading model.
5673      *
5674      * @param    l   the mouse listener
5675      * @see      java.awt.event.MouseEvent
5676      * @see      java.awt.event.MouseListener
5677      * @see      #addMouseListener
5678      * @see      #getMouseListeners
5679      * @since    1.1
5680      */
5681     public synchronized void removeMouseListener(MouseListener l) {
5682         if (l == null) {
5683             return;
5684         }
5685         mouseListener = AWTEventMulticaster.remove(mouseListener, l);
5686     }
5687 
5688     /**
5689      * Returns an array of all the mouse listeners
5690      * registered on this component.
5691      *
5692      * @return all of this component's <code>MouseListener</code>s
5693      *         or an empty array if no mouse
5694      *         listeners are currently registered
5695      *
5696      * @see      #addMouseListener
5697      * @see      #removeMouseListener
5698      * @since    1.4
5699      */
5700     public synchronized MouseListener[] getMouseListeners() {
5701         return getListeners(MouseListener.class);
5702     }
5703 
5704     /**
5705      * Adds the specified mouse motion listener to receive mouse motion
5706      * events from this component.
5707      * If listener <code>l</code> is <code>null</code>,
5708      * no exception is thrown and no action is performed.
5709      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5710      * >AWT Threading Issues</a> for details on AWT's threading model.
5711      *
5712      * @param    l   the mouse motion listener
5713      * @see      java.awt.event.MouseEvent
5714      * @see      java.awt.event.MouseMotionListener
5715      * @see      #removeMouseMotionListener
5716      * @see      #getMouseMotionListeners
5717      * @since    1.1
5718      */
5719     public synchronized void addMouseMotionListener(MouseMotionListener l) {
5720         if (l == null) {
5721             return;
5722         }
5723         mouseMotionListener = AWTEventMulticaster.add(mouseMotionListener,l);
5724         newEventsOnly = true;
5725 
5726         // if this is a lightweight component, enable mouse events
5727         // in the native container.
5728         if (peer instanceof LightweightPeer) {
5729             parent.proxyEnableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
5730         }
5731     }
5732 
5733     /**
5734      * Removes the specified mouse motion listener so that it no longer
5735      * receives mouse motion events from this component. This method performs
5736      * no function, nor does it throw an exception, if the listener
5737      * specified by the argument was not previously added to this component.
5738      * If listener <code>l</code> is <code>null</code>,
5739      * no exception is thrown and no action is performed.
5740      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5741      * >AWT Threading Issues</a> for details on AWT's threading model.
5742      *
5743      * @param    l   the mouse motion listener
5744      * @see      java.awt.event.MouseEvent
5745      * @see      java.awt.event.MouseMotionListener
5746      * @see      #addMouseMotionListener
5747      * @see      #getMouseMotionListeners
5748      * @since    1.1
5749      */
5750     public synchronized void removeMouseMotionListener(MouseMotionListener l) {
5751         if (l == null) {
5752             return;
5753         }
5754         mouseMotionListener = AWTEventMulticaster.remove(mouseMotionListener, l);
5755     }
5756 
5757     /**
5758      * Returns an array of all the mouse motion listeners
5759      * registered on this component.
5760      *
5761      * @return all of this component's <code>MouseMotionListener</code>s
5762      *         or an empty array if no mouse motion
5763      *         listeners are currently registered
5764      *
5765      * @see      #addMouseMotionListener
5766      * @see      #removeMouseMotionListener
5767      * @since    1.4
5768      */
5769     public synchronized MouseMotionListener[] getMouseMotionListeners() {
5770         return getListeners(MouseMotionListener.class);
5771     }
5772 
5773     /**
5774      * Adds the specified mouse wheel listener to receive mouse wheel events
5775      * from this component.  Containers also receive mouse wheel events from
5776      * sub-components.
5777      * <p>
5778      * For information on how mouse wheel events are dispatched, see
5779      * the class description for {@link MouseWheelEvent}.
5780      * <p>
5781      * If l is <code>null</code>, no exception is thrown and no
5782      * action is performed.
5783      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5784      * >AWT Threading Issues</a> for details on AWT's threading model.
5785      *
5786      * @param    l   the mouse wheel listener
5787      * @see      java.awt.event.MouseWheelEvent
5788      * @see      java.awt.event.MouseWheelListener
5789      * @see      #removeMouseWheelListener
5790      * @see      #getMouseWheelListeners
5791      * @since    1.4
5792      */
5793     public synchronized void addMouseWheelListener(MouseWheelListener l) {
5794         if (l == null) {
5795             return;
5796         }
5797         mouseWheelListener = AWTEventMulticaster.add(mouseWheelListener,l);
5798         newEventsOnly = true;
5799 
5800         // if this is a lightweight component, enable mouse events
5801         // in the native container.
5802         if (peer instanceof LightweightPeer) {
5803             parent.proxyEnableEvents(AWTEvent.MOUSE_WHEEL_EVENT_MASK);
5804         }
5805     }
5806 
5807     /**
5808      * Removes the specified mouse wheel listener so that it no longer
5809      * receives mouse wheel events from this component. This method performs
5810      * no function, nor does it throw an exception, if the listener
5811      * specified by the argument was not previously added to this component.
5812      * If l is null, no exception is thrown and no action is performed.
5813      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5814      * >AWT Threading Issues</a> for details on AWT's threading model.
5815      *
5816      * @param    l   the mouse wheel listener.
5817      * @see      java.awt.event.MouseWheelEvent
5818      * @see      java.awt.event.MouseWheelListener
5819      * @see      #addMouseWheelListener
5820      * @see      #getMouseWheelListeners
5821      * @since    1.4
5822      */
5823     public synchronized void removeMouseWheelListener(MouseWheelListener l) {
5824         if (l == null) {
5825             return;
5826         }
5827         mouseWheelListener = AWTEventMulticaster.remove(mouseWheelListener, l);
5828     }
5829 
5830     /**
5831      * Returns an array of all the mouse wheel listeners
5832      * registered on this component.
5833      *
5834      * @return all of this component's <code>MouseWheelListener</code>s
5835      *         or an empty array if no mouse wheel
5836      *         listeners are currently registered
5837      *
5838      * @see      #addMouseWheelListener
5839      * @see      #removeMouseWheelListener
5840      * @since    1.4
5841      */
5842     public synchronized MouseWheelListener[] getMouseWheelListeners() {
5843         return getListeners(MouseWheelListener.class);
5844     }
5845 
5846     /**
5847      * Adds the specified input method listener to receive
5848      * input method events from this component. A component will
5849      * only receive input method events from input methods
5850      * if it also overrides <code>getInputMethodRequests</code> to return an
5851      * <code>InputMethodRequests</code> instance.
5852      * If listener <code>l</code> is <code>null</code>,
5853      * no exception is thrown and no action is performed.
5854      * <p>Refer to <a href="{@docRoot}/java/awt/doc-files/AWTThreadIssues.html#ListenersThreads"
5855      * >AWT Threading Issues</a> for details on AWT's threading model.
5856      *
5857      * @param    l   the input method listener
5858      * @see      java.awt.event.InputMethodEvent
5859      * @see      java.awt.event.InputMethodListener
5860      * @see      #removeInputMethodListener
5861      * @see      #getInputMethodListeners
5862      * @see      #getInputMethodRequests
5863      * @since    1.2
5864      */
5865     public synchronized void addInputMethodListener(InputMethodListener l) {
5866         if (l == null) {
5867             return;
5868         }
5869         inputMethodListener = AWTEventMulticaster.add(inputMethodListener, l);
5870         newEventsOnly = true;
5871     }
5872 
5873     /**
5874      * Removes the specified input method listener so that it no longer
5875      * receives input method events from this component. This method performs
5876      * no function, nor does it throw an exception, if the listener
5877      * specified by the argument was not previously added to this component.
5878      * If listener <code>l</code> is <code>null</code>,
5879      * no exception is thrown and no action is performed.
5880      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5881      * >AWT Threading Issues</a> for details on AWT's threading model.
5882      *
5883      * @param    l   the input method listener
5884      * @see      java.awt.event.InputMethodEvent
5885      * @see      java.awt.event.InputMethodListener
5886      * @see      #addInputMethodListener
5887      * @see      #getInputMethodListeners
5888      * @since    1.2
5889      */
5890     public synchronized void removeInputMethodListener(InputMethodListener l) {
5891         if (l == null) {
5892             return;
5893         }
5894         inputMethodListener = AWTEventMulticaster.remove(inputMethodListener, l);
5895     }
5896 
5897     /**
5898      * Returns an array of all the input method listeners
5899      * registered on this component.
5900      *
5901      * @return all of this component's <code>InputMethodListener</code>s
5902      *         or an empty array if no input method
5903      *         listeners are currently registered
5904      *
5905      * @see      #addInputMethodListener
5906      * @see      #removeInputMethodListener
5907      * @since    1.4
5908      */
5909     public synchronized InputMethodListener[] getInputMethodListeners() {
5910         return getListeners(InputMethodListener.class);
5911     }
5912 
5913     /**
5914      * Returns an array of all the objects currently registered
5915      * as <code><em>Foo</em>Listener</code>s
5916      * upon this <code>Component</code>.
5917      * <code><em>Foo</em>Listener</code>s are registered using the
5918      * <code>add<em>Foo</em>Listener</code> method.
5919      *
5920      * <p>
5921      * You can specify the <code>listenerType</code> argument
5922      * with a class literal, such as
5923      * <code><em>Foo</em>Listener.class</code>.
5924      * For example, you can query a
5925      * <code>Component</code> <code>c</code>
5926      * for its mouse listeners with the following code:
5927      *
5928      * <pre>MouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class));</pre>
5929      *
5930      * If no such listeners exist, this method returns an empty array.
5931      *
5932      * @param listenerType the type of listeners requested; this parameter
5933      *          should specify an interface that descends from
5934      *          <code>java.util.EventListener</code>
5935      * @return an array of all objects registered as
5936      *          <code><em>Foo</em>Listener</code>s on this component,
5937      *          or an empty array if no such listeners have been added
5938      * @exception ClassCastException if <code>listenerType</code>
5939      *          doesn't specify a class or interface that implements
5940      *          <code>java.util.EventListener</code>
5941      * @throws NullPointerException if {@code listenerType} is {@code null}
5942      * @see #getComponentListeners
5943      * @see #getFocusListeners
5944      * @see #getHierarchyListeners
5945      * @see #getHierarchyBoundsListeners
5946      * @see #getKeyListeners
5947      * @see #getMouseListeners
5948      * @see #getMouseMotionListeners
5949      * @see #getMouseWheelListeners
5950      * @see #getInputMethodListeners
5951      * @see #getPropertyChangeListeners
5952      *
5953      * @since 1.3
5954      */
5955     @SuppressWarnings("unchecked")
5956     public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
5957         EventListener l = null;
5958         if  (listenerType == ComponentListener.class) {
5959             l = componentListener;
5960         } else if (listenerType == FocusListener.class) {
5961             l = focusListener;
5962         } else if (listenerType == HierarchyListener.class) {
5963             l = hierarchyListener;
5964         } else if (listenerType == HierarchyBoundsListener.class) {
5965             l = hierarchyBoundsListener;
5966         } else if (listenerType == KeyListener.class) {
5967             l = keyListener;
5968         } else if (listenerType == MouseListener.class) {
5969             l = mouseListener;
5970         } else if (listenerType == MouseMotionListener.class) {
5971             l = mouseMotionListener;
5972         } else if (listenerType == MouseWheelListener.class) {
5973             l = mouseWheelListener;
5974         } else if (listenerType == InputMethodListener.class) {
5975             l = inputMethodListener;
5976         } else if (listenerType == PropertyChangeListener.class) {
5977             return (T[])getPropertyChangeListeners();
5978         }
5979         return AWTEventMulticaster.getListeners(l, listenerType);
5980     }
5981 
5982     /**
5983      * Gets the input method request handler which supports
5984      * requests from input methods for this component. A component
5985      * that supports on-the-spot text input must override this
5986      * method to return an <code>InputMethodRequests</code> instance.
5987      * At the same time, it also has to handle input method events.
5988      *
5989      * @return the input method request handler for this component,
5990      *          <code>null</code> by default
5991      * @see #addInputMethodListener
5992      * @since 1.2
5993      */
5994     public InputMethodRequests getInputMethodRequests() {
5995         return null;
5996     }
5997 
5998     /**
5999      * Gets the input context used by this component for handling
6000      * the communication with input methods when text is entered
6001      * in this component. By default, the input context used for
6002      * the parent component is returned. Components may
6003      * override this to return a private input context.
6004      *
6005      * @return the input context used by this component;
6006      *          <code>null</code> if no context can be determined
6007      * @since 1.2
6008      */
6009     public InputContext getInputContext() {
6010         Container parent = this.parent;
6011         if (parent == null) {
6012             return null;
6013         } else {
6014             return parent.getInputContext();
6015         }
6016     }
6017 
6018     /**
6019      * Enables the events defined by the specified event mask parameter
6020      * to be delivered to this component.
6021      * <p>
6022      * Event types are automatically enabled when a listener for
6023      * that event type is added to the component.
6024      * <p>
6025      * This method only needs to be invoked by subclasses of
6026      * <code>Component</code> which desire to have the specified event
6027      * types delivered to <code>processEvent</code> regardless of whether
6028      * or not a listener is registered.
6029      * @param      eventsToEnable   the event mask defining the event types
6030      * @see        #processEvent
6031      * @see        #disableEvents
6032      * @see        AWTEvent
6033      * @since      1.1
6034      */
6035     protected final void enableEvents(long eventsToEnable) {
6036         long notifyAncestors = 0;
6037         synchronized (this) {
6038             if ((eventsToEnable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 &&
6039                 hierarchyListener == null &&
6040                 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0) {
6041                 notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK;
6042             }
6043             if ((eventsToEnable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 &&
6044                 hierarchyBoundsListener == null &&
6045                 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0) {
6046                 notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK;
6047             }
6048             eventMask |= eventsToEnable;
6049             newEventsOnly = true;
6050         }
6051 
6052         // if this is a lightweight component, enable mouse events
6053         // in the native container.
6054         if (peer instanceof LightweightPeer) {
6055             parent.proxyEnableEvents(eventMask);
6056         }
6057         if (notifyAncestors != 0) {
6058             synchronized (getTreeLock()) {
6059                 adjustListeningChildrenOnParent(notifyAncestors, 1);
6060             }
6061         }
6062     }
6063 
6064     /**
6065      * Disables the events defined by the specified event mask parameter
6066      * from being delivered to this component.
6067      * @param      eventsToDisable   the event mask defining the event types
6068      * @see        #enableEvents
6069      * @since      1.1
6070      */
6071     protected final void disableEvents(long eventsToDisable) {
6072         long notifyAncestors = 0;
6073         synchronized (this) {
6074             if ((eventsToDisable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 &&
6075                 hierarchyListener == null &&
6076                 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0) {
6077                 notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK;
6078             }
6079             if ((eventsToDisable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK)!=0 &&
6080                 hierarchyBoundsListener == null &&
6081                 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0) {
6082                 notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK;
6083             }
6084             eventMask &= ~eventsToDisable;
6085         }
6086         if (notifyAncestors != 0) {
6087             synchronized (getTreeLock()) {
6088                 adjustListeningChildrenOnParent(notifyAncestors, -1);
6089             }
6090         }
6091     }
6092 
6093     transient sun.awt.EventQueueItem[] eventCache;
6094 
6095     /**
6096      * @see #isCoalescingEnabled
6097      * @see #checkCoalescing
6098      */
6099     transient private boolean coalescingEnabled = checkCoalescing();
6100 
6101     /**
6102      * Weak map of known coalesceEvent overriders.
6103      * Value indicates whether overriden.
6104      * Bootstrap classes are not included.
6105      */
6106     private static final Map<Class<?>, Boolean> coalesceMap =
6107         new java.util.WeakHashMap<Class<?>, Boolean>();
6108 
6109     /**
6110      * Indicates whether this class overrides coalesceEvents.
6111      * It is assumed that all classes that are loaded from the bootstrap
6112      *   do not.
6113      * The boostrap class loader is assumed to be represented by null.
6114      * We do not check that the method really overrides
6115      *   (it might be static, private or package private).
6116      */
6117      private boolean checkCoalescing() {
6118          if (getClass().getClassLoader()==null) {
6119              return false;
6120          }
6121          final Class<? extends Component> clazz = getClass();
6122          synchronized (coalesceMap) {
6123              // Check cache.
6124              Boolean value = coalesceMap.get(clazz);
6125              if (value != null) {
6126                  return value;
6127              }
6128 
6129              // Need to check non-bootstraps.
6130              Boolean enabled = java.security.AccessController.doPrivileged(
6131                  new java.security.PrivilegedAction<Boolean>() {
6132                      public Boolean run() {
6133                          return isCoalesceEventsOverriden(clazz);
6134                      }
6135                  }
6136                  );
6137              coalesceMap.put(clazz, enabled);
6138              return enabled;
6139          }
6140      }
6141 
6142     /**
6143      * Parameter types of coalesceEvents(AWTEvent,AWTEVent).
6144      */
6145     private static final Class<?>[] coalesceEventsParams = {
6146         AWTEvent.class, AWTEvent.class
6147     };
6148 
6149     /**
6150      * Indicates whether a class or its superclasses override coalesceEvents.
6151      * Must be called with lock on coalesceMap and privileged.
6152      * @see checkCoalsecing
6153      */
6154     private static boolean isCoalesceEventsOverriden(Class<?> clazz) {
6155         assert Thread.holdsLock(coalesceMap);
6156 
6157         // First check superclass - we may not need to bother ourselves.
6158         Class<?> superclass = clazz.getSuperclass();
6159         if (superclass == null) {
6160             // Only occurs on implementations that
6161             //   do not use null to represent the bootsrap class loader.
6162             return false;
6163         }
6164         if (superclass.getClassLoader() != null) {
6165             Boolean value = coalesceMap.get(superclass);
6166             if (value == null) {
6167                 // Not done already - recurse.
6168                 if (isCoalesceEventsOverriden(superclass)) {
6169                     coalesceMap.put(superclass, true);
6170                     return true;
6171                 }
6172             } else if (value) {
6173                 return true;
6174             }
6175         }
6176 
6177         try {
6178             // Throws if not overriden.
6179             clazz.getDeclaredMethod(
6180                 "coalesceEvents", coalesceEventsParams
6181                 );
6182             return true;
6183         } catch (NoSuchMethodException e) {
6184             // Not present in this class.
6185             return false;
6186         }
6187     }
6188 
6189     /**
6190      * Indicates whether coalesceEvents may do something.
6191      */
6192     final boolean isCoalescingEnabled() {
6193         return coalescingEnabled;
6194      }
6195 
6196 
6197     /**
6198      * Potentially coalesce an event being posted with an existing
6199      * event.  This method is called by <code>EventQueue.postEvent</code>
6200      * if an event with the same ID as the event to be posted is found in
6201      * the queue (both events must have this component as their source).
6202      * This method either returns a coalesced event which replaces
6203      * the existing event (and the new event is then discarded), or
6204      * <code>null</code> to indicate that no combining should be done
6205      * (add the second event to the end of the queue).  Either event
6206      * parameter may be modified and returned, as the other one is discarded
6207      * unless <code>null</code> is returned.
6208      * <p>
6209      * This implementation of <code>coalesceEvents</code> coalesces
6210      * two event types: mouse move (and drag) events,
6211      * and paint (and update) events.
6212      * For mouse move events the last event is always returned, causing
6213      * intermediate moves to be discarded.  For paint events, the new
6214      * event is coalesced into a complex <code>RepaintArea</code> in the peer.
6215      * The new <code>AWTEvent</code> is always returned.
6216      *
6217      * @param  existingEvent  the event already on the <code>EventQueue</code>
6218      * @param  newEvent       the event being posted to the
6219      *          <code>EventQueue</code>
6220      * @return a coalesced event, or <code>null</code> indicating that no
6221      *          coalescing was done
6222      */
6223     protected AWTEvent coalesceEvents(AWTEvent existingEvent,
6224                                       AWTEvent newEvent) {
6225         return null;
6226     }
6227 
6228     /**
6229      * Processes events occurring on this component. By default this
6230      * method calls the appropriate
6231      * <code>process&lt;event&nbsp;type&gt;Event</code>
6232      * method for the given class of event.
6233      * <p>Note that if the event parameter is <code>null</code>
6234      * the behavior is unspecified and may result in an
6235      * exception.
6236      *
6237      * @param     e the event
6238      * @see       #processComponentEvent
6239      * @see       #processFocusEvent
6240      * @see       #processKeyEvent
6241      * @see       #processMouseEvent
6242      * @see       #processMouseMotionEvent
6243      * @see       #processInputMethodEvent
6244      * @see       #processHierarchyEvent
6245      * @see       #processMouseWheelEvent
6246      * @since     1.1
6247      */
6248     protected void processEvent(AWTEvent e) {
6249         if (e instanceof FocusEvent) {
6250             processFocusEvent((FocusEvent)e);
6251 
6252         } else if (e instanceof MouseEvent) {
6253             switch(e.getID()) {
6254               case MouseEvent.MOUSE_PRESSED:
6255               case MouseEvent.MOUSE_RELEASED:
6256               case MouseEvent.MOUSE_CLICKED:
6257               case MouseEvent.MOUSE_ENTERED:
6258               case MouseEvent.MOUSE_EXITED:
6259                   processMouseEvent((MouseEvent)e);
6260                   break;
6261               case MouseEvent.MOUSE_MOVED:
6262               case MouseEvent.MOUSE_DRAGGED:
6263                   processMouseMotionEvent((MouseEvent)e);
6264                   break;
6265               case MouseEvent.MOUSE_WHEEL:
6266                   processMouseWheelEvent((MouseWheelEvent)e);
6267                   break;
6268             }
6269 
6270         } else if (e instanceof KeyEvent) {
6271             processKeyEvent((KeyEvent)e);
6272 
6273         } else if (e instanceof ComponentEvent) {
6274             processComponentEvent((ComponentEvent)e);
6275         } else if (e instanceof InputMethodEvent) {
6276             processInputMethodEvent((InputMethodEvent)e);
6277         } else if (e instanceof HierarchyEvent) {
6278             switch (e.getID()) {
6279               case HierarchyEvent.HIERARCHY_CHANGED:
6280                   processHierarchyEvent((HierarchyEvent)e);
6281                   break;
6282               case HierarchyEvent.ANCESTOR_MOVED:
6283               case HierarchyEvent.ANCESTOR_RESIZED:
6284                   processHierarchyBoundsEvent((HierarchyEvent)e);
6285                   break;
6286             }
6287         }
6288     }
6289 
6290     /**
6291      * Processes component events occurring on this component by
6292      * dispatching them to any registered
6293      * <code>ComponentListener</code> objects.
6294      * <p>
6295      * This method is not called unless component events are
6296      * enabled for this component. Component events are enabled
6297      * when one of the following occurs:
6298      * <ul>
6299      * <li>A <code>ComponentListener</code> object is registered
6300      * via <code>addComponentListener</code>.
6301      * <li>Component events are enabled via <code>enableEvents</code>.
6302      * </ul>
6303      * <p>Note that if the event parameter is <code>null</code>
6304      * the behavior is unspecified and may result in an
6305      * exception.
6306      *
6307      * @param       e the component event
6308      * @see         java.awt.event.ComponentEvent
6309      * @see         java.awt.event.ComponentListener
6310      * @see         #addComponentListener
6311      * @see         #enableEvents
6312      * @since       1.1
6313      */
6314     protected void processComponentEvent(ComponentEvent e) {
6315         ComponentListener listener = componentListener;
6316         if (listener != null) {
6317             int id = e.getID();
6318             switch(id) {
6319               case ComponentEvent.COMPONENT_RESIZED:
6320                   listener.componentResized(e);
6321                   break;
6322               case ComponentEvent.COMPONENT_MOVED:
6323                   listener.componentMoved(e);
6324                   break;
6325               case ComponentEvent.COMPONENT_SHOWN:
6326                   listener.componentShown(e);
6327                   break;
6328               case ComponentEvent.COMPONENT_HIDDEN:
6329                   listener.componentHidden(e);
6330                   break;
6331             }
6332         }
6333     }
6334 
6335     /**
6336      * Processes focus events occurring on this component by
6337      * dispatching them to any registered
6338      * <code>FocusListener</code> objects.
6339      * <p>
6340      * This method is not called unless focus events are
6341      * enabled for this component. Focus events are enabled
6342      * when one of the following occurs:
6343      * <ul>
6344      * <li>A <code>FocusListener</code> object is registered
6345      * via <code>addFocusListener</code>.
6346      * <li>Focus events are enabled via <code>enableEvents</code>.
6347      * </ul>
6348      * <p>
6349      * If focus events are enabled for a <code>Component</code>,
6350      * the current <code>KeyboardFocusManager</code> determines
6351      * whether or not a focus event should be dispatched to
6352      * registered <code>FocusListener</code> objects.  If the
6353      * events are to be dispatched, the <code>KeyboardFocusManager</code>
6354      * calls the <code>Component</code>'s <code>dispatchEvent</code>
6355      * method, which results in a call to the <code>Component</code>'s
6356      * <code>processFocusEvent</code> method.
6357      * <p>
6358      * If focus events are enabled for a <code>Component</code>, calling
6359      * the <code>Component</code>'s <code>dispatchEvent</code> method
6360      * with a <code>FocusEvent</code> as the argument will result in a
6361      * call to the <code>Component</code>'s <code>processFocusEvent</code>
6362      * method regardless of the current <code>KeyboardFocusManager</code>.
6363      *
6364      * <p>Note that if the event parameter is <code>null</code>
6365      * the behavior is unspecified and may result in an
6366      * exception.
6367      *
6368      * @param       e the focus event
6369      * @see         java.awt.event.FocusEvent
6370      * @see         java.awt.event.FocusListener
6371      * @see         java.awt.KeyboardFocusManager
6372      * @see         #addFocusListener
6373      * @see         #enableEvents
6374      * @see         #dispatchEvent
6375      * @since       1.1
6376      */
6377     protected void processFocusEvent(FocusEvent e) {
6378         FocusListener listener = focusListener;
6379         if (listener != null) {
6380             int id = e.getID();
6381             switch(id) {
6382               case FocusEvent.FOCUS_GAINED:
6383                   listener.focusGained(e);
6384                   break;
6385               case FocusEvent.FOCUS_LOST:
6386                   listener.focusLost(e);
6387                   break;
6388             }
6389         }
6390     }
6391 
6392     /**
6393      * Processes key events occurring on this component by
6394      * dispatching them to any registered
6395      * <code>KeyListener</code> objects.
6396      * <p>
6397      * This method is not called unless key events are
6398      * enabled for this component. Key events are enabled
6399      * when one of the following occurs:
6400      * <ul>
6401      * <li>A <code>KeyListener</code> object is registered
6402      * via <code>addKeyListener</code>.
6403      * <li>Key events are enabled via <code>enableEvents</code>.
6404      * </ul>
6405      *
6406      * <p>
6407      * If key events are enabled for a <code>Component</code>,
6408      * the current <code>KeyboardFocusManager</code> determines
6409      * whether or not a key event should be dispatched to
6410      * registered <code>KeyListener</code> objects.  The
6411      * <code>DefaultKeyboardFocusManager</code> will not dispatch
6412      * key events to a <code>Component</code> that is not the focus
6413      * owner or is not showing.
6414      * <p>
6415      * As of J2SE 1.4, <code>KeyEvent</code>s are redirected to
6416      * the focus owner. Please see the
6417      * <a href="doc-files/FocusSpec.html">Focus Specification</a>
6418      * for further information.
6419      * <p>
6420      * Calling a <code>Component</code>'s <code>dispatchEvent</code>
6421      * method with a <code>KeyEvent</code> as the argument will
6422      * result in a call to the <code>Component</code>'s
6423      * <code>processKeyEvent</code> method regardless of the
6424      * current <code>KeyboardFocusManager</code> as long as the
6425      * component is showing, focused, and enabled, and key events
6426      * are enabled on it.
6427      * <p>If the event parameter is <code>null</code>
6428      * the behavior is unspecified and may result in an
6429      * exception.
6430      *
6431      * @param       e the key event
6432      * @see         java.awt.event.KeyEvent
6433      * @see         java.awt.event.KeyListener
6434      * @see         java.awt.KeyboardFocusManager
6435      * @see         java.awt.DefaultKeyboardFocusManager
6436      * @see         #processEvent
6437      * @see         #dispatchEvent
6438      * @see         #addKeyListener
6439      * @see         #enableEvents
6440      * @see         #isShowing
6441      * @since       1.1
6442      */
6443     protected void processKeyEvent(KeyEvent e) {
6444         KeyListener listener = keyListener;
6445         if (listener != null) {
6446             int id = e.getID();
6447             switch(id) {
6448               case KeyEvent.KEY_TYPED:
6449                   listener.keyTyped(e);
6450                   break;
6451               case KeyEvent.KEY_PRESSED:
6452                   listener.keyPressed(e);
6453                   break;
6454               case KeyEvent.KEY_RELEASED:
6455                   listener.keyReleased(e);
6456                   break;
6457             }
6458         }
6459     }
6460 
6461     /**
6462      * Processes mouse events occurring on this component by
6463      * dispatching them to any registered
6464      * <code>MouseListener</code> objects.
6465      * <p>
6466      * This method is not called unless mouse events are
6467      * enabled for this component. Mouse events are enabled
6468      * when one of the following occurs:
6469      * <ul>
6470      * <li>A <code>MouseListener</code> object is registered
6471      * via <code>addMouseListener</code>.
6472      * <li>Mouse events are enabled via <code>enableEvents</code>.
6473      * </ul>
6474      * <p>Note that if the event parameter is <code>null</code>
6475      * the behavior is unspecified and may result in an
6476      * exception.
6477      *
6478      * @param       e the mouse event
6479      * @see         java.awt.event.MouseEvent
6480      * @see         java.awt.event.MouseListener
6481      * @see         #addMouseListener
6482      * @see         #enableEvents
6483      * @since       1.1
6484      */
6485     protected void processMouseEvent(MouseEvent e) {
6486         MouseListener listener = mouseListener;
6487         if (listener != null) {
6488             int id = e.getID();
6489             switch(id) {
6490               case MouseEvent.MOUSE_PRESSED:
6491                   listener.mousePressed(e);
6492                   break;
6493               case MouseEvent.MOUSE_RELEASED:
6494                   listener.mouseReleased(e);
6495                   break;
6496               case MouseEvent.MOUSE_CLICKED:
6497                   listener.mouseClicked(e);
6498                   break;
6499               case MouseEvent.MOUSE_EXITED:
6500                   listener.mouseExited(e);
6501                   break;
6502               case MouseEvent.MOUSE_ENTERED:
6503                   listener.mouseEntered(e);
6504                   break;
6505             }
6506         }
6507     }
6508 
6509     /**
6510      * Processes mouse motion events occurring on this component by
6511      * dispatching them to any registered
6512      * <code>MouseMotionListener</code> objects.
6513      * <p>
6514      * This method is not called unless mouse motion events are
6515      * enabled for this component. Mouse motion events are enabled
6516      * when one of the following occurs:
6517      * <ul>
6518      * <li>A <code>MouseMotionListener</code> object is registered
6519      * via <code>addMouseMotionListener</code>.
6520      * <li>Mouse motion events are enabled via <code>enableEvents</code>.
6521      * </ul>
6522      * <p>Note that if the event parameter is <code>null</code>
6523      * the behavior is unspecified and may result in an
6524      * exception.
6525      *
6526      * @param       e the mouse motion event
6527      * @see         java.awt.event.MouseEvent
6528      * @see         java.awt.event.MouseMotionListener
6529      * @see         #addMouseMotionListener
6530      * @see         #enableEvents
6531      * @since       1.1
6532      */
6533     protected void processMouseMotionEvent(MouseEvent e) {
6534         MouseMotionListener listener = mouseMotionListener;
6535         if (listener != null) {
6536             int id = e.getID();
6537             switch(id) {
6538               case MouseEvent.MOUSE_MOVED:
6539                   listener.mouseMoved(e);
6540                   break;
6541               case MouseEvent.MOUSE_DRAGGED:
6542                   listener.mouseDragged(e);
6543                   break;
6544             }
6545         }
6546     }
6547 
6548     /**
6549      * Processes mouse wheel events occurring on this component by
6550      * dispatching them to any registered
6551      * <code>MouseWheelListener</code> objects.
6552      * <p>
6553      * This method is not called unless mouse wheel events are
6554      * enabled for this component. Mouse wheel events are enabled
6555      * when one of the following occurs:
6556      * <ul>
6557      * <li>A <code>MouseWheelListener</code> object is registered
6558      * via <code>addMouseWheelListener</code>.
6559      * <li>Mouse wheel events are enabled via <code>enableEvents</code>.
6560      * </ul>
6561      * <p>
6562      * For information on how mouse wheel events are dispatched, see
6563      * the class description for {@link MouseWheelEvent}.
6564      * <p>
6565      * Note that if the event parameter is <code>null</code>
6566      * the behavior is unspecified and may result in an
6567      * exception.
6568      *
6569      * @param       e the mouse wheel event
6570      * @see         java.awt.event.MouseWheelEvent
6571      * @see         java.awt.event.MouseWheelListener
6572      * @see         #addMouseWheelListener
6573      * @see         #enableEvents
6574      * @since       1.4
6575      */
6576     protected void processMouseWheelEvent(MouseWheelEvent e) {
6577         MouseWheelListener listener = mouseWheelListener;
6578         if (listener != null) {
6579             int id = e.getID();
6580             switch(id) {
6581               case MouseEvent.MOUSE_WHEEL:
6582                   listener.mouseWheelMoved(e);
6583                   break;
6584             }
6585         }
6586     }
6587 
6588     boolean postsOldMouseEvents() {
6589         return false;
6590     }
6591 
6592     /**
6593      * Processes input method events occurring on this component by
6594      * dispatching them to any registered
6595      * <code>InputMethodListener</code> objects.
6596      * <p>
6597      * This method is not called unless input method events
6598      * are enabled for this component. Input method events are enabled
6599      * when one of the following occurs:
6600      * <ul>
6601      * <li>An <code>InputMethodListener</code> object is registered
6602      * via <code>addInputMethodListener</code>.
6603      * <li>Input method events are enabled via <code>enableEvents</code>.
6604      * </ul>
6605      * <p>Note that if the event parameter is <code>null</code>
6606      * the behavior is unspecified and may result in an
6607      * exception.
6608      *
6609      * @param       e the input method event
6610      * @see         java.awt.event.InputMethodEvent
6611      * @see         java.awt.event.InputMethodListener
6612      * @see         #addInputMethodListener
6613      * @see         #enableEvents
6614      * @since       1.2
6615      */
6616     protected void processInputMethodEvent(InputMethodEvent e) {
6617         InputMethodListener listener = inputMethodListener;
6618         if (listener != null) {
6619             int id = e.getID();
6620             switch (id) {
6621               case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED:
6622                   listener.inputMethodTextChanged(e);
6623                   break;
6624               case InputMethodEvent.CARET_POSITION_CHANGED:
6625                   listener.caretPositionChanged(e);
6626                   break;
6627             }
6628         }
6629     }
6630 
6631     /**
6632      * Processes hierarchy events occurring on this component by
6633      * dispatching them to any registered
6634      * <code>HierarchyListener</code> objects.
6635      * <p>
6636      * This method is not called unless hierarchy events
6637      * are enabled for this component. Hierarchy events are enabled
6638      * when one of the following occurs:
6639      * <ul>
6640      * <li>An <code>HierarchyListener</code> object is registered
6641      * via <code>addHierarchyListener</code>.
6642      * <li>Hierarchy 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 hierarchy event
6649      * @see         java.awt.event.HierarchyEvent
6650      * @see         java.awt.event.HierarchyListener
6651      * @see         #addHierarchyListener
6652      * @see         #enableEvents
6653      * @since       1.3
6654      */
6655     protected void processHierarchyEvent(HierarchyEvent e) {
6656         HierarchyListener listener = hierarchyListener;
6657         if (listener != null) {
6658             int id = e.getID();
6659             switch (id) {
6660               case HierarchyEvent.HIERARCHY_CHANGED:
6661                   listener.hierarchyChanged(e);
6662                   break;
6663             }
6664         }
6665     }
6666 
6667     /**
6668      * Processes hierarchy bounds events occurring on this component by
6669      * dispatching them to any registered
6670      * <code>HierarchyBoundsListener</code> objects.
6671      * <p>
6672      * This method is not called unless hierarchy bounds events
6673      * are enabled for this component. Hierarchy bounds events are enabled
6674      * when one of the following occurs:
6675      * <ul>
6676      * <li>An <code>HierarchyBoundsListener</code> object is registered
6677      * via <code>addHierarchyBoundsListener</code>.
6678      * <li>Hierarchy bounds events are enabled via <code>enableEvents</code>.
6679      * </ul>
6680      * <p>Note that if the event parameter is <code>null</code>
6681      * the behavior is unspecified and may result in an
6682      * exception.
6683      *
6684      * @param       e the hierarchy event
6685      * @see         java.awt.event.HierarchyEvent
6686      * @see         java.awt.event.HierarchyBoundsListener
6687      * @see         #addHierarchyBoundsListener
6688      * @see         #enableEvents
6689      * @since       1.3
6690      */
6691     protected void processHierarchyBoundsEvent(HierarchyEvent e) {
6692         HierarchyBoundsListener listener = hierarchyBoundsListener;
6693         if (listener != null) {
6694             int id = e.getID();
6695             switch (id) {
6696               case HierarchyEvent.ANCESTOR_MOVED:
6697                   listener.ancestorMoved(e);
6698                   break;
6699               case HierarchyEvent.ANCESTOR_RESIZED:
6700                   listener.ancestorResized(e);
6701                   break;
6702             }
6703         }
6704     }
6705 
6706     /**
6707      * @deprecated As of JDK version 1.1
6708      * replaced by processEvent(AWTEvent).
6709      */
6710     @Deprecated
6711     public boolean handleEvent(Event evt) {
6712         switch (evt.id) {
6713           case Event.MOUSE_ENTER:
6714               return mouseEnter(evt, evt.x, evt.y);
6715 
6716           case Event.MOUSE_EXIT:
6717               return mouseExit(evt, evt.x, evt.y);
6718 
6719           case Event.MOUSE_MOVE:
6720               return mouseMove(evt, evt.x, evt.y);
6721 
6722           case Event.MOUSE_DOWN:
6723               return mouseDown(evt, evt.x, evt.y);
6724 
6725           case Event.MOUSE_DRAG:
6726               return mouseDrag(evt, evt.x, evt.y);
6727 
6728           case Event.MOUSE_UP:
6729               return mouseUp(evt, evt.x, evt.y);
6730 
6731           case Event.KEY_PRESS:
6732           case Event.KEY_ACTION:
6733               return keyDown(evt, evt.key);
6734 
6735           case Event.KEY_RELEASE:
6736           case Event.KEY_ACTION_RELEASE:
6737               return keyUp(evt, evt.key);
6738 
6739           case Event.ACTION_EVENT:
6740               return action(evt, evt.arg);
6741           case Event.GOT_FOCUS:
6742               return gotFocus(evt, evt.arg);
6743           case Event.LOST_FOCUS:
6744               return lostFocus(evt, evt.arg);
6745         }
6746         return false;
6747     }
6748 
6749     /**
6750      * @deprecated As of JDK version 1.1,
6751      * replaced by processMouseEvent(MouseEvent).
6752      */
6753     @Deprecated
6754     public boolean mouseDown(Event evt, int x, int y) {
6755         return false;
6756     }
6757 
6758     /**
6759      * @deprecated As of JDK version 1.1,
6760      * replaced by processMouseMotionEvent(MouseEvent).
6761      */
6762     @Deprecated
6763     public boolean mouseDrag(Event evt, int x, int y) {
6764         return false;
6765     }
6766 
6767     /**
6768      * @deprecated As of JDK version 1.1,
6769      * replaced by processMouseEvent(MouseEvent).
6770      */
6771     @Deprecated
6772     public boolean mouseUp(Event evt, int x, int y) {
6773         return false;
6774     }
6775 
6776     /**
6777      * @deprecated As of JDK version 1.1,
6778      * replaced by processMouseMotionEvent(MouseEvent).
6779      */
6780     @Deprecated
6781     public boolean mouseMove(Event evt, int x, int y) {
6782         return false;
6783     }
6784 
6785     /**
6786      * @deprecated As of JDK version 1.1,
6787      * replaced by processMouseEvent(MouseEvent).
6788      */
6789     @Deprecated
6790     public boolean mouseEnter(Event evt, int x, int y) {
6791         return false;
6792     }
6793 
6794     /**
6795      * @deprecated As of JDK version 1.1,
6796      * replaced by processMouseEvent(MouseEvent).
6797      */
6798     @Deprecated
6799     public boolean mouseExit(Event evt, int x, int y) {
6800         return false;
6801     }
6802 
6803     /**
6804      * @deprecated As of JDK version 1.1,
6805      * replaced by processKeyEvent(KeyEvent).
6806      */
6807     @Deprecated
6808     public boolean keyDown(Event evt, int key) {
6809         return false;
6810     }
6811 
6812     /**
6813      * @deprecated As of JDK version 1.1,
6814      * replaced by processKeyEvent(KeyEvent).
6815      */
6816     @Deprecated
6817     public boolean keyUp(Event evt, int key) {
6818         return false;
6819     }
6820 
6821     /**
6822      * @deprecated As of JDK version 1.1,
6823      * should register this component as ActionListener on component
6824      * which fires action events.
6825      */
6826     @Deprecated
6827     public boolean action(Event evt, Object what) {
6828         return false;
6829     }
6830 
6831     /**
6832      * Makes this <code>Component</code> displayable by connecting it to a
6833      * native screen resource.
6834      * This method is called internally by the toolkit and should
6835      * not be called directly by programs.
6836      * <p>
6837      * This method changes layout-related information, and therefore,
6838      * invalidates the component hierarchy.
6839      *
6840      * @see       #isDisplayable
6841      * @see       #removeNotify
6842      * @see #invalidate
6843      * @since 1.0
6844      */
6845     public void addNotify() {
6846         synchronized (getTreeLock()) {
6847             ComponentPeer peer = this.peer;
6848             if (peer == null || peer instanceof LightweightPeer){
6849                 if (peer == null) {
6850                     // Update both the Component's peer variable and the local
6851                     // variable we use for thread safety.
6852                     this.peer = peer = getToolkit().createComponent(this);
6853                 }
6854 
6855                 // This is a lightweight component which means it won't be
6856                 // able to get window-related events by itself.  If any
6857                 // have been enabled, then the nearest native container must
6858                 // be enabled.
6859                 if (parent != null) {
6860                     long mask = 0;
6861                     if ((mouseListener != null) || ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0)) {
6862                         mask |= AWTEvent.MOUSE_EVENT_MASK;
6863                     }
6864                     if ((mouseMotionListener != null) ||
6865                         ((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0)) {
6866                         mask |= AWTEvent.MOUSE_MOTION_EVENT_MASK;
6867                     }
6868                     if ((mouseWheelListener != null ) ||
6869                         ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0)) {
6870                         mask |= AWTEvent.MOUSE_WHEEL_EVENT_MASK;
6871                     }
6872                     if (focusListener != null || (eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0) {
6873                         mask |= AWTEvent.FOCUS_EVENT_MASK;
6874                     }
6875                     if (keyListener != null || (eventMask & AWTEvent.KEY_EVENT_MASK) != 0) {
6876                         mask |= AWTEvent.KEY_EVENT_MASK;
6877                     }
6878                     if (mask != 0) {
6879                         parent.proxyEnableEvents(mask);
6880                     }
6881                 }
6882             } else {
6883                 // It's native. If the parent is lightweight it will need some
6884                 // help.
6885                 Container parent = getContainer();
6886                 if (parent != null && parent.isLightweight()) {
6887                     relocateComponent();
6888                     if (!parent.isRecursivelyVisibleUpToHeavyweightContainer())
6889                     {
6890                         peer.setVisible(false);
6891                     }
6892                 }
6893             }
6894             invalidate();
6895 
6896             int npopups = (popups != null? popups.size() : 0);
6897             for (int i = 0 ; i < npopups ; i++) {
6898                 PopupMenu popup = popups.elementAt(i);
6899                 popup.addNotify();
6900             }
6901 
6902             if (dropTarget != null) dropTarget.addNotify(peer);
6903 
6904             peerFont = getFont();
6905 
6906             if (getContainer() != null && !isAddNotifyComplete) {
6907                 getContainer().increaseComponentCount(this);
6908             }
6909 
6910 
6911             // Update stacking order
6912             updateZOrder();
6913 
6914             if (!isAddNotifyComplete) {
6915                 mixOnShowing();
6916             }
6917 
6918             isAddNotifyComplete = true;
6919 
6920             if (hierarchyListener != null ||
6921                 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
6922                 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) {
6923                 HierarchyEvent e =
6924                     new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED,
6925                                        this, parent,
6926                                        HierarchyEvent.DISPLAYABILITY_CHANGED |
6927                                        ((isRecursivelyVisible())
6928                                         ? HierarchyEvent.SHOWING_CHANGED
6929                                         : 0));
6930                 dispatchEvent(e);
6931             }
6932         }
6933     }
6934 
6935     /**
6936      * Makes this <code>Component</code> undisplayable by destroying it native
6937      * screen resource.
6938      * <p>
6939      * This method is called by the toolkit internally and should
6940      * not be called directly by programs. Code overriding
6941      * this method should call <code>super.removeNotify</code> as
6942      * the first line of the overriding method.
6943      *
6944      * @see       #isDisplayable
6945      * @see       #addNotify
6946      * @since 1.0
6947      */
6948     public void removeNotify() {
6949         KeyboardFocusManager.clearMostRecentFocusOwner(this);
6950         if (KeyboardFocusManager.getCurrentKeyboardFocusManager().
6951             getPermanentFocusOwner() == this)
6952         {
6953             KeyboardFocusManager.getCurrentKeyboardFocusManager().
6954                 setGlobalPermanentFocusOwner(null);
6955         }
6956 
6957         synchronized (getTreeLock()) {
6958             clearLightweightDispatcherOnRemove(this);
6959 
6960             if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabledFor(this)) {
6961                 transferFocus(true);
6962             }
6963 
6964             if (getContainer() != null && isAddNotifyComplete) {
6965                 getContainer().decreaseComponentCount(this);
6966             }
6967 
6968             int npopups = (popups != null? popups.size() : 0);
6969             for (int i = 0 ; i < npopups ; i++) {
6970                 PopupMenu popup = popups.elementAt(i);
6971                 popup.removeNotify();
6972             }
6973             // If there is any input context for this component, notify
6974             // that this component is being removed. (This has to be done
6975             // before hiding peer.)
6976             if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) {
6977                 InputContext inputContext = getInputContext();
6978                 if (inputContext != null) {
6979                     inputContext.removeNotify(this);
6980                 }
6981             }
6982 
6983             ComponentPeer p = peer;
6984             if (p != null) {
6985                 boolean isLightweight = isLightweight();
6986 
6987                 if (bufferStrategy instanceof FlipBufferStrategy) {
6988                     ((FlipBufferStrategy)bufferStrategy).destroyBuffers();
6989                 }
6990 
6991                 if (dropTarget != null) dropTarget.removeNotify(peer);
6992 
6993                 // Hide peer first to stop system events such as cursor moves.
6994                 if (visible) {
6995                     p.setVisible(false);
6996                 }
6997 
6998                 peer = null; // Stop peer updates.
6999                 peerFont = null;
7000 
7001                 Toolkit.getEventQueue().removeSourceEvents(this, false);
7002                 KeyboardFocusManager.getCurrentKeyboardFocusManager().
7003                     discardKeyEvents(this);
7004 
7005                 p.dispose();
7006 
7007                 mixOnHiding(isLightweight);
7008 
7009                 isAddNotifyComplete = false;
7010                 // Nullifying compoundShape means that the component has normal shape
7011                 // (or has no shape at all).
7012                 this.compoundShape = null;
7013             }
7014 
7015             if (hierarchyListener != null ||
7016                 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
7017                 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) {
7018                 HierarchyEvent e =
7019                     new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED,
7020                                        this, parent,
7021                                        HierarchyEvent.DISPLAYABILITY_CHANGED |
7022                                        ((isRecursivelyVisible())
7023                                         ? HierarchyEvent.SHOWING_CHANGED
7024                                         : 0));
7025                 dispatchEvent(e);
7026             }
7027         }
7028     }
7029 
7030     /**
7031      * @deprecated As of JDK version 1.1,
7032      * replaced by processFocusEvent(FocusEvent).
7033      */
7034     @Deprecated
7035     public boolean gotFocus(Event evt, Object what) {
7036         return false;
7037     }
7038 
7039     /**
7040      * @deprecated As of JDK version 1.1,
7041      * replaced by processFocusEvent(FocusEvent).
7042      */
7043     @Deprecated
7044     public boolean lostFocus(Event evt, Object what) {
7045         return false;
7046     }
7047 
7048     /**
7049      * Returns whether this <code>Component</code> can become the focus
7050      * owner.
7051      *
7052      * @return <code>true</code> if this <code>Component</code> is
7053      * focusable; <code>false</code> otherwise
7054      * @see #setFocusable
7055      * @since 1.1
7056      * @deprecated As of 1.4, replaced by <code>isFocusable()</code>.
7057      */
7058     @Deprecated
7059     public boolean isFocusTraversable() {
7060         if (isFocusTraversableOverridden == FOCUS_TRAVERSABLE_UNKNOWN) {
7061             isFocusTraversableOverridden = FOCUS_TRAVERSABLE_DEFAULT;
7062         }
7063         return focusable;
7064     }
7065 
7066     /**
7067      * Returns whether this Component can be focused.
7068      *
7069      * @return <code>true</code> if this Component is focusable;
7070      *         <code>false</code> otherwise.
7071      * @see #setFocusable
7072      * @since 1.4
7073      */
7074     public boolean isFocusable() {
7075         return isFocusTraversable();
7076     }
7077 
7078     /**
7079      * Sets the focusable state of this Component to the specified value. This
7080      * value overrides the Component's default focusability.
7081      *
7082      * @param focusable indicates whether this Component is focusable
7083      * @see #isFocusable
7084      * @since 1.4
7085      * @beaninfo
7086      *       bound: true
7087      */
7088     public void setFocusable(boolean focusable) {
7089         boolean oldFocusable;
7090         synchronized (this) {
7091             oldFocusable = this.focusable;
7092             this.focusable = focusable;
7093         }
7094         isFocusTraversableOverridden = FOCUS_TRAVERSABLE_SET;
7095 
7096         firePropertyChange("focusable", oldFocusable, focusable);
7097         if (oldFocusable && !focusable) {
7098             if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabled()) {
7099                 transferFocus(true);
7100             }
7101             KeyboardFocusManager.clearMostRecentFocusOwner(this);
7102         }
7103     }
7104 
7105     final boolean isFocusTraversableOverridden() {
7106         return (isFocusTraversableOverridden != FOCUS_TRAVERSABLE_DEFAULT);
7107     }
7108 
7109     /**
7110      * Sets the focus traversal keys for a given traversal operation for this
7111      * Component.
7112      * <p>
7113      * The default values for a Component's focus traversal keys are
7114      * implementation-dependent. Sun recommends that all implementations for a
7115      * particular native platform use the same default values. The
7116      * recommendations for Windows and Unix are listed below. These
7117      * recommendations are used in the Sun AWT implementations.
7118      *
7119      * <table border=1 summary="Recommended default values for a Component's focus traversal keys">
7120      * <tr>
7121      *    <th>Identifier</th>
7122      *    <th>Meaning</th>
7123      *    <th>Default</th>
7124      * </tr>
7125      * <tr>
7126      *    <td>KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS</td>
7127      *    <td>Normal forward keyboard traversal</td>
7128      *    <td>TAB on KEY_PRESSED, CTRL-TAB on KEY_PRESSED</td>
7129      * </tr>
7130      * <tr>
7131      *    <td>KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS</td>
7132      *    <td>Normal reverse keyboard traversal</td>
7133      *    <td>SHIFT-TAB on KEY_PRESSED, CTRL-SHIFT-TAB on KEY_PRESSED</td>
7134      * </tr>
7135      * <tr>
7136      *    <td>KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS</td>
7137      *    <td>Go up one focus traversal cycle</td>
7138      *    <td>none</td>
7139      * </tr>
7140      * </table>
7141      *
7142      * To disable a traversal key, use an empty Set; Collections.EMPTY_SET is
7143      * recommended.
7144      * <p>
7145      * Using the AWTKeyStroke API, client code can specify on which of two
7146      * specific KeyEvents, KEY_PRESSED or KEY_RELEASED, the focus traversal
7147      * operation will occur. Regardless of which KeyEvent is specified,
7148      * however, all KeyEvents related to the focus traversal key, including the
7149      * associated KEY_TYPED event, will be consumed, and will not be dispatched
7150      * to any Component. It is a runtime error to specify a KEY_TYPED event as
7151      * mapping to a focus traversal operation, or to map the same event to
7152      * multiple default focus traversal operations.
7153      * <p>
7154      * If a value of null is specified for the Set, this Component inherits the
7155      * Set from its parent. If all ancestors of this Component have null
7156      * specified for the Set, then the current KeyboardFocusManager's default
7157      * Set is used.
7158      * <p>
7159      * This method may throw a {@code ClassCastException} if any {@code Object}
7160      * in {@code keystrokes} is not an {@code AWTKeyStroke}.
7161      *
7162      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7163      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7164      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7165      * @param keystrokes the Set of AWTKeyStroke for the specified operation
7166      * @see #getFocusTraversalKeys
7167      * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
7168      * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
7169      * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
7170      * @throws IllegalArgumentException if id is not one of
7171      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7172      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7173      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or if keystrokes
7174      *         contains null, or if any keystroke represents a KEY_TYPED event,
7175      *         or if any keystroke already maps to another focus traversal
7176      *         operation for this Component
7177      * @since 1.4
7178      * @beaninfo
7179      *       bound: true
7180      */
7181     public void setFocusTraversalKeys(int id,
7182                                       Set<? extends AWTKeyStroke> keystrokes)
7183     {
7184         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {
7185             throw new IllegalArgumentException("invalid focus traversal key identifier");
7186         }
7187 
7188         setFocusTraversalKeys_NoIDCheck(id, keystrokes);
7189     }
7190 
7191     /**
7192      * Returns the Set of focus traversal keys for a given traversal operation
7193      * for this Component. (See
7194      * <code>setFocusTraversalKeys</code> for a full description of each key.)
7195      * <p>
7196      * If a Set of traversal keys has not been explicitly defined for this
7197      * Component, then this Component's parent's Set is returned. If no Set
7198      * has been explicitly defined for any of this Component's ancestors, then
7199      * the current KeyboardFocusManager's default Set is returned.
7200      *
7201      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7202      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7203      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7204      * @return the Set of AWTKeyStrokes for the specified operation. The Set
7205      *         will be unmodifiable, and may be empty. null will never be
7206      *         returned.
7207      * @see #setFocusTraversalKeys
7208      * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
7209      * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
7210      * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
7211      * @throws IllegalArgumentException if id is not one of
7212      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7213      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7214      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7215      * @since 1.4
7216      */
7217     public Set<AWTKeyStroke> getFocusTraversalKeys(int id) {
7218         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {
7219             throw new IllegalArgumentException("invalid focus traversal key identifier");
7220         }
7221 
7222         return getFocusTraversalKeys_NoIDCheck(id);
7223     }
7224 
7225     // We define these methods so that Container does not need to repeat this
7226     // code. Container cannot call super.<method> because Container allows
7227     // DOWN_CYCLE_TRAVERSAL_KEY while Component does not. The Component method
7228     // would erroneously generate an IllegalArgumentException for
7229     // DOWN_CYCLE_TRAVERSAL_KEY.
7230     final void setFocusTraversalKeys_NoIDCheck(int id, Set<? extends AWTKeyStroke> keystrokes) {
7231         Set<AWTKeyStroke> oldKeys;
7232 
7233         synchronized (this) {
7234             if (focusTraversalKeys == null) {
7235                 initializeFocusTraversalKeys();
7236             }
7237 
7238             if (keystrokes != null) {
7239                 for (AWTKeyStroke keystroke : keystrokes ) {
7240 
7241                     if (keystroke == null) {
7242                         throw new IllegalArgumentException("cannot set null focus traversal key");
7243                     }
7244 
7245                     if (keystroke.getKeyChar() != KeyEvent.CHAR_UNDEFINED) {
7246                         throw new IllegalArgumentException("focus traversal keys cannot map to KEY_TYPED events");
7247                     }
7248 
7249                     for (int i = 0; i < focusTraversalKeys.length; i++) {
7250                         if (i == id) {
7251                             continue;
7252                         }
7253 
7254                         if (getFocusTraversalKeys_NoIDCheck(i).contains(keystroke))
7255                         {
7256                             throw new IllegalArgumentException("focus traversal keys must be unique for a Component");
7257                         }
7258                     }
7259                 }
7260             }
7261 
7262             oldKeys = focusTraversalKeys[id];
7263             focusTraversalKeys[id] = (keystrokes != null)
7264                 ? Collections.unmodifiableSet(new HashSet<AWTKeyStroke>(keystrokes))
7265                 : null;
7266         }
7267 
7268         firePropertyChange(focusTraversalKeyPropertyNames[id], oldKeys,
7269                            keystrokes);
7270     }
7271     final Set<AWTKeyStroke> getFocusTraversalKeys_NoIDCheck(int id) {
7272         // Okay to return Set directly because it is an unmodifiable view
7273         @SuppressWarnings("unchecked")
7274         Set<AWTKeyStroke> keystrokes = (focusTraversalKeys != null)
7275             ? focusTraversalKeys[id]
7276             : null;
7277 
7278         if (keystrokes != null) {
7279             return keystrokes;
7280         } else {
7281             Container parent = this.parent;
7282             if (parent != null) {
7283                 return parent.getFocusTraversalKeys(id);
7284             } else {
7285                 return KeyboardFocusManager.getCurrentKeyboardFocusManager().
7286                     getDefaultFocusTraversalKeys(id);
7287             }
7288         }
7289     }
7290 
7291     /**
7292      * Returns whether the Set of focus traversal keys for the given focus
7293      * traversal operation has been explicitly defined for this Component. If
7294      * this method returns <code>false</code>, this Component is inheriting the
7295      * Set from an ancestor, or from the current KeyboardFocusManager.
7296      *
7297      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7298      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7299      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7300      * @return <code>true</code> if the the Set of focus traversal keys for the
7301      *         given focus traversal operation has been explicitly defined for
7302      *         this Component; <code>false</code> otherwise.
7303      * @throws IllegalArgumentException if id is not one of
7304      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7305      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7306      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7307      * @since 1.4
7308      */
7309     public boolean areFocusTraversalKeysSet(int id) {
7310         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {
7311             throw new IllegalArgumentException("invalid focus traversal key identifier");
7312         }
7313 
7314         return (focusTraversalKeys != null && focusTraversalKeys[id] != null);
7315     }
7316 
7317     /**
7318      * Sets whether focus traversal keys are enabled for this Component.
7319      * Components for which focus traversal keys are disabled receive key
7320      * events for focus traversal keys. Components for which focus traversal
7321      * keys are enabled do not see these events; instead, the events are
7322      * automatically converted to traversal operations.
7323      *
7324      * @param focusTraversalKeysEnabled whether focus traversal keys are
7325      *        enabled for this Component
7326      * @see #getFocusTraversalKeysEnabled
7327      * @see #setFocusTraversalKeys
7328      * @see #getFocusTraversalKeys
7329      * @since 1.4
7330      * @beaninfo
7331      *       bound: true
7332      */
7333     public void setFocusTraversalKeysEnabled(boolean
7334                                              focusTraversalKeysEnabled) {
7335         boolean oldFocusTraversalKeysEnabled;
7336         synchronized (this) {
7337             oldFocusTraversalKeysEnabled = this.focusTraversalKeysEnabled;
7338             this.focusTraversalKeysEnabled = focusTraversalKeysEnabled;
7339         }
7340         firePropertyChange("focusTraversalKeysEnabled",
7341                            oldFocusTraversalKeysEnabled,
7342                            focusTraversalKeysEnabled);
7343     }
7344 
7345     /**
7346      * Returns whether focus traversal keys are enabled for this Component.
7347      * Components for which focus traversal keys are disabled receive key
7348      * events for focus traversal keys. Components for which focus traversal
7349      * keys are enabled do not see these events; instead, the events are
7350      * automatically converted to traversal operations.
7351      *
7352      * @return whether focus traversal keys are enabled for this Component
7353      * @see #setFocusTraversalKeysEnabled
7354      * @see #setFocusTraversalKeys
7355      * @see #getFocusTraversalKeys
7356      * @since 1.4
7357      */
7358     public boolean getFocusTraversalKeysEnabled() {
7359         return focusTraversalKeysEnabled;
7360     }
7361 
7362     /**
7363      * Requests that this Component get the input focus, and that this
7364      * Component's top-level ancestor become the focused Window. This
7365      * component must be displayable, focusable, visible and all of
7366      * its ancestors (with the exception of the top-level Window) must
7367      * be visible for the request to be granted. Every effort will be
7368      * made to honor the request; however, in some cases it may be
7369      * impossible to do so. Developers must never assume that this
7370      * Component is the focus owner until this Component receives a
7371      * FOCUS_GAINED event. If this request is denied because this
7372      * Component's top-level Window cannot become the focused Window,
7373      * the request will be remembered and will be granted when the
7374      * Window is later focused by the user.
7375      * <p>
7376      * This method cannot be used to set the focus owner to no Component at
7377      * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code>
7378      * instead.
7379      * <p>
7380      * Because the focus behavior of this method is platform-dependent,
7381      * developers are strongly encouraged to use
7382      * <code>requestFocusInWindow</code> when possible.
7383      *
7384      * <p>Note: Not all focus transfers result from invoking this method. As
7385      * such, a component may receive focus without this or any of the other
7386      * {@code requestFocus} methods of {@code Component} being invoked.
7387      *
7388      * @see #requestFocusInWindow
7389      * @see java.awt.event.FocusEvent
7390      * @see #addFocusListener
7391      * @see #isFocusable
7392      * @see #isDisplayable
7393      * @see KeyboardFocusManager#clearGlobalFocusOwner
7394      * @since 1.0
7395      */
7396     public void requestFocus() {
7397         requestFocusHelper(false, true);
7398     }
7399 
7400     boolean requestFocus(CausedFocusEvent.Cause cause) {
7401         return requestFocusHelper(false, true, cause);
7402     }
7403 
7404     /**
7405      * Requests that this <code>Component</code> get the input focus,
7406      * and that this <code>Component</code>'s top-level ancestor
7407      * become the focused <code>Window</code>. This component must be
7408      * displayable, focusable, visible and all of its ancestors (with
7409      * the exception of the top-level Window) must be visible for the
7410      * request to be granted. Every effort will be made to honor the
7411      * request; however, in some cases it may be impossible to do
7412      * so. Developers must never assume that this component is the
7413      * focus owner until this component receives a FOCUS_GAINED
7414      * event. If this request is denied because this component's
7415      * top-level window cannot become the focused window, the request
7416      * will be remembered and will be granted when the window is later
7417      * focused by the user.
7418      * <p>
7419      * This method returns a boolean value. If <code>false</code> is returned,
7420      * the request is <b>guaranteed to fail</b>. If <code>true</code> is
7421      * returned, the request will succeed <b>unless</b> it is vetoed, or an
7422      * extraordinary event, such as disposal of the component's peer, occurs
7423      * before the request can be granted by the native windowing system. Again,
7424      * while a return value of <code>true</code> indicates that the request is
7425      * likely to succeed, developers must never assume that this component is
7426      * the focus owner until this component receives a FOCUS_GAINED event.
7427      * <p>
7428      * This method cannot be used to set the focus owner to no component at
7429      * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner</code>
7430      * instead.
7431      * <p>
7432      * Because the focus behavior of this method is platform-dependent,
7433      * developers are strongly encouraged to use
7434      * <code>requestFocusInWindow</code> when possible.
7435      * <p>
7436      * Every effort will be made to ensure that <code>FocusEvent</code>s
7437      * generated as a
7438      * result of this request will have the specified temporary value. However,
7439      * because specifying an arbitrary temporary state may not be implementable
7440      * on all native windowing systems, correct behavior for this method can be
7441      * guaranteed only for lightweight <code>Component</code>s.
7442      * This method is not intended
7443      * for general use, but exists instead as a hook for lightweight component
7444      * libraries, such as Swing.
7445      *
7446      * <p>Note: Not all focus transfers result from invoking this method. As
7447      * such, a component may receive focus without this or any of the other
7448      * {@code requestFocus} methods of {@code Component} being invoked.
7449      *
7450      * @param temporary true if the focus change is temporary,
7451      *        such as when the window loses the focus; for
7452      *        more information on temporary focus changes see the
7453      *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
7454      * @return <code>false</code> if the focus change request is guaranteed to
7455      *         fail; <code>true</code> if it is likely to succeed
7456      * @see java.awt.event.FocusEvent
7457      * @see #addFocusListener
7458      * @see #isFocusable
7459      * @see #isDisplayable
7460      * @see KeyboardFocusManager#clearGlobalFocusOwner
7461      * @since 1.4
7462      */
7463     protected boolean requestFocus(boolean temporary) {
7464         return requestFocusHelper(temporary, true);
7465     }
7466 
7467     boolean requestFocus(boolean temporary, CausedFocusEvent.Cause cause) {
7468         return requestFocusHelper(temporary, true, cause);
7469     }
7470     /**
7471      * Requests that this Component get the input focus, if this
7472      * Component's top-level ancestor is already the focused
7473      * Window. This component must be displayable, focusable, visible
7474      * and all of its ancestors (with the exception of the top-level
7475      * Window) must be visible for the request to be granted. Every
7476      * effort will be made to honor the request; however, in some
7477      * cases it may be impossible to do so. Developers must never
7478      * assume that this Component is the focus owner until this
7479      * Component receives a FOCUS_GAINED event.
7480      * <p>
7481      * This method returns a boolean value. If <code>false</code> is returned,
7482      * the request is <b>guaranteed to fail</b>. If <code>true</code> is
7483      * returned, the request will succeed <b>unless</b> it is vetoed, or an
7484      * extraordinary event, such as disposal of the Component's peer, occurs
7485      * before the request can be granted by the native windowing system. Again,
7486      * while a return value of <code>true</code> indicates that the request is
7487      * likely to succeed, developers must never assume that this Component is
7488      * the focus owner until this Component receives a FOCUS_GAINED event.
7489      * <p>
7490      * This method cannot be used to set the focus owner to no Component at
7491      * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code>
7492      * instead.
7493      * <p>
7494      * The focus behavior of this method can be implemented uniformly across
7495      * platforms, and thus developers are strongly encouraged to use this
7496      * method over <code>requestFocus</code> when possible. Code which relies
7497      * on <code>requestFocus</code> may exhibit different focus behavior on
7498      * different platforms.
7499      *
7500      * <p>Note: Not all focus transfers result from invoking this method. As
7501      * such, a component may receive focus without this or any of the other
7502      * {@code requestFocus} methods of {@code Component} being invoked.
7503      *
7504      * @return <code>false</code> if the focus change request is guaranteed to
7505      *         fail; <code>true</code> if it is likely to succeed
7506      * @see #requestFocus
7507      * @see java.awt.event.FocusEvent
7508      * @see #addFocusListener
7509      * @see #isFocusable
7510      * @see #isDisplayable
7511      * @see KeyboardFocusManager#clearGlobalFocusOwner
7512      * @since 1.4
7513      */
7514     public boolean requestFocusInWindow() {
7515         return requestFocusHelper(false, false);
7516     }
7517 
7518     boolean requestFocusInWindow(CausedFocusEvent.Cause cause) {
7519         return requestFocusHelper(false, false, cause);
7520     }
7521 
7522     /**
7523      * Requests that this <code>Component</code> get the input focus,
7524      * if this <code>Component</code>'s top-level ancestor is already
7525      * the focused <code>Window</code>.  This component must be
7526      * displayable, focusable, visible and all of its ancestors (with
7527      * the exception of the top-level Window) must be visible for the
7528      * request to be granted. Every effort will be made to honor the
7529      * request; however, in some cases it may be impossible to do
7530      * so. Developers must never assume that this component is the
7531      * focus owner until this component receives a FOCUS_GAINED event.
7532      * <p>
7533      * This method returns a boolean value. If <code>false</code> is returned,
7534      * the request is <b>guaranteed to fail</b>. If <code>true</code> is
7535      * returned, the request will succeed <b>unless</b> it is vetoed, or an
7536      * extraordinary event, such as disposal of the component's peer, occurs
7537      * before the request can be granted by the native windowing system. Again,
7538      * while a return value of <code>true</code> indicates that the request is
7539      * likely to succeed, developers must never assume that this component is
7540      * the focus owner until this component receives a FOCUS_GAINED event.
7541      * <p>
7542      * This method cannot be used to set the focus owner to no component at
7543      * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner</code>
7544      * instead.
7545      * <p>
7546      * The focus behavior of this method can be implemented uniformly across
7547      * platforms, and thus developers are strongly encouraged to use this
7548      * method over <code>requestFocus</code> when possible. Code which relies
7549      * on <code>requestFocus</code> may exhibit different focus behavior on
7550      * different platforms.
7551      * <p>
7552      * Every effort will be made to ensure that <code>FocusEvent</code>s
7553      * generated as a
7554      * result of this request will have the specified temporary value. However,
7555      * because specifying an arbitrary temporary state may not be implementable
7556      * on all native windowing systems, correct behavior for this method can be
7557      * guaranteed only for lightweight components. This method is not intended
7558      * for general use, but exists instead as a hook for lightweight component
7559      * libraries, such as Swing.
7560      *
7561      * <p>Note: Not all focus transfers result from invoking this method. As
7562      * such, a component may receive focus without this or any of the other
7563      * {@code requestFocus} methods of {@code Component} being invoked.
7564      *
7565      * @param temporary true if the focus change is temporary,
7566      *        such as when the window loses the focus; for
7567      *        more information on temporary focus changes see the
7568      *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
7569      * @return <code>false</code> if the focus change request is guaranteed to
7570      *         fail; <code>true</code> if it is likely to succeed
7571      * @see #requestFocus
7572      * @see java.awt.event.FocusEvent
7573      * @see #addFocusListener
7574      * @see #isFocusable
7575      * @see #isDisplayable
7576      * @see KeyboardFocusManager#clearGlobalFocusOwner
7577      * @since 1.4
7578      */
7579     protected boolean requestFocusInWindow(boolean temporary) {
7580         return requestFocusHelper(temporary, false);
7581     }
7582 
7583     boolean requestFocusInWindow(boolean temporary, CausedFocusEvent.Cause cause) {
7584         return requestFocusHelper(temporary, false, cause);
7585     }
7586 
7587     final boolean requestFocusHelper(boolean temporary,
7588                                      boolean focusedWindowChangeAllowed) {
7589         return requestFocusHelper(temporary, focusedWindowChangeAllowed, CausedFocusEvent.Cause.UNKNOWN);
7590     }
7591 
7592     final boolean requestFocusHelper(boolean temporary,
7593                                      boolean focusedWindowChangeAllowed,
7594                                      CausedFocusEvent.Cause cause)
7595     {
7596         // 1) Check if the event being dispatched is a system-generated mouse event.
7597         AWTEvent currentEvent = EventQueue.getCurrentEvent();
7598         if (currentEvent instanceof MouseEvent &&
7599             SunToolkit.isSystemGenerated(currentEvent))
7600         {
7601             // 2) Sanity check: if the mouse event component source belongs to the same containing window.
7602             Component source = ((MouseEvent)currentEvent).getComponent();
7603             if (source == null || source.getContainingWindow() == getContainingWindow()) {
7604                 focusLog.finest("requesting focus by mouse event \"in window\"");
7605 
7606                 // If both the conditions are fulfilled the focus request should be strictly
7607                 // bounded by the toplevel window. It's assumed that the mouse event activates
7608                 // the window (if it wasn't active) and this makes it possible for a focus
7609                 // request with a strong in-window requirement to change focus in the bounds
7610                 // of the toplevel. If, by any means, due to asynchronous nature of the event
7611                 // dispatching mechanism, the window happens to be natively inactive by the time
7612                 // this focus request is eventually handled, it should not re-activate the
7613                 // toplevel. Otherwise the result may not meet user expectations. See 6981400.
7614                 focusedWindowChangeAllowed = false;
7615             }
7616         }
7617         if (!isRequestFocusAccepted(temporary, focusedWindowChangeAllowed, cause)) {
7618             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7619                 focusLog.finest("requestFocus is not accepted");
7620             }
7621             return false;
7622         }
7623         // Update most-recent map
7624         KeyboardFocusManager.setMostRecentFocusOwner(this);
7625 
7626         Component window = this;
7627         while ( (window != null) && !(window instanceof Window)) {
7628             if (!window.isVisible()) {
7629                 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7630                     focusLog.finest("component is recurively invisible");
7631                 }
7632                 return false;
7633             }
7634             window = window.parent;
7635         }
7636 
7637         ComponentPeer peer = this.peer;
7638         Component heavyweight = (peer instanceof LightweightPeer)
7639             ? getNativeContainer() : this;
7640         if (heavyweight == null || !heavyweight.isVisible()) {
7641             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7642                 focusLog.finest("Component is not a part of visible hierarchy");
7643             }
7644             return false;
7645         }
7646         peer = heavyweight.peer;
7647         if (peer == null) {
7648             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7649                 focusLog.finest("Peer is null");
7650             }
7651             return false;
7652         }
7653 
7654         // Focus this Component
7655         long time = 0;
7656         if (EventQueue.isDispatchThread()) {
7657             time = Toolkit.getEventQueue().getMostRecentKeyEventTime();
7658         } else {
7659             // A focus request made from outside EDT should not be associated with any event
7660             // and so its time stamp is simply set to the current time.
7661             time = System.currentTimeMillis();
7662         }
7663 
7664         boolean success = peer.requestFocus
7665             (this, temporary, focusedWindowChangeAllowed, time, cause);
7666         if (!success) {
7667             KeyboardFocusManager.getCurrentKeyboardFocusManager
7668                 (appContext).dequeueKeyEvents(time, this);
7669             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7670                 focusLog.finest("Peer request failed");
7671             }
7672         } else {
7673             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7674                 focusLog.finest("Pass for " + this);
7675             }
7676         }
7677         return success;
7678     }
7679 
7680     private boolean isRequestFocusAccepted(boolean temporary,
7681                                            boolean focusedWindowChangeAllowed,
7682                                            CausedFocusEvent.Cause cause)
7683     {
7684         if (!isFocusable() || !isVisible()) {
7685             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7686                 focusLog.finest("Not focusable or not visible");
7687             }
7688             return false;
7689         }
7690 
7691         ComponentPeer peer = this.peer;
7692         if (peer == null) {
7693             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7694                 focusLog.finest("peer is null");
7695             }
7696             return false;
7697         }
7698 
7699         Window window = getContainingWindow();
7700         if (window == null || !window.isFocusableWindow()) {
7701             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7702                 focusLog.finest("Component doesn't have toplevel");
7703             }
7704             return false;
7705         }
7706 
7707         // We have passed all regular checks for focus request,
7708         // now let's call RequestFocusController and see what it says.
7709         Component focusOwner = KeyboardFocusManager.getMostRecentFocusOwner(window);
7710         if (focusOwner == null) {
7711             // sometimes most recent focus owner may be null, but focus owner is not
7712             // e.g. we reset most recent focus owner if user removes focus owner
7713             focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
7714             if (focusOwner != null && focusOwner.getContainingWindow() != window) {
7715                 focusOwner = null;
7716             }
7717         }
7718 
7719         if (focusOwner == this || focusOwner == null) {
7720             // Controller is supposed to verify focus transfers and for this it
7721             // should know both from and to components.  And it shouldn't verify
7722             // transfers from when these components are equal.
7723             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7724                 focusLog.finest("focus owner is null or this");
7725             }
7726             return true;
7727         }
7728 
7729         if (CausedFocusEvent.Cause.ACTIVATION == cause) {
7730             // we shouldn't call RequestFocusController in case we are
7731             // in activation.  We do request focus on component which
7732             // has got temporary focus lost and then on component which is
7733             // most recent focus owner.  But most recent focus owner can be
7734             // changed by requestFocsuXXX() call only, so this transfer has
7735             // been already approved.
7736             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7737                 focusLog.finest("cause is activation");
7738             }
7739             return true;
7740         }
7741 
7742         boolean ret = Component.requestFocusController.acceptRequestFocus(focusOwner,
7743                                                                           this,
7744                                                                           temporary,
7745                                                                           focusedWindowChangeAllowed,
7746                                                                           cause);
7747         if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7748             focusLog.finest("RequestFocusController returns {0}", ret);
7749         }
7750 
7751         return ret;
7752     }
7753 
7754     private static RequestFocusController requestFocusController = new DummyRequestFocusController();
7755 
7756     // Swing access this method through reflection to implement InputVerifier's functionality.
7757     // Perhaps, we should make this method public (later ;)
7758     private static class DummyRequestFocusController implements RequestFocusController {
7759         public boolean acceptRequestFocus(Component from, Component to,
7760                                           boolean temporary, boolean focusedWindowChangeAllowed,
7761                                           CausedFocusEvent.Cause cause)
7762         {
7763             return true;
7764         }
7765     };
7766 
7767     synchronized static void setRequestFocusController(RequestFocusController requestController)
7768     {
7769         if (requestController == null) {
7770             requestFocusController = new DummyRequestFocusController();
7771         } else {
7772             requestFocusController = requestController;
7773         }
7774     }
7775 
7776     /**
7777      * Returns the Container which is the focus cycle root of this Component's
7778      * focus traversal cycle. Each focus traversal cycle has only a single
7779      * focus cycle root and each Component which is not a Container belongs to
7780      * only a single focus traversal cycle. Containers which are focus cycle
7781      * roots belong to two cycles: one rooted at the Container itself, and one
7782      * rooted at the Container's nearest focus-cycle-root ancestor. For such
7783      * Containers, this method will return the Container's nearest focus-cycle-
7784      * root ancestor.
7785      *
7786      * @return this Component's nearest focus-cycle-root ancestor
7787      * @see Container#isFocusCycleRoot()
7788      * @since 1.4
7789      */
7790     public Container getFocusCycleRootAncestor() {
7791         Container rootAncestor = this.parent;
7792         while (rootAncestor != null && !rootAncestor.isFocusCycleRoot()) {
7793             rootAncestor = rootAncestor.parent;
7794         }
7795         return rootAncestor;
7796     }
7797 
7798     /**
7799      * Returns whether the specified Container is the focus cycle root of this
7800      * Component's focus traversal cycle. Each focus traversal cycle has only
7801      * a single focus cycle root and each Component which is not a Container
7802      * belongs to only a single focus traversal cycle.
7803      *
7804      * @param container the Container to be tested
7805      * @return <code>true</code> if the specified Container is a focus-cycle-
7806      *         root of this Component; <code>false</code> otherwise
7807      * @see Container#isFocusCycleRoot()
7808      * @since 1.4
7809      */
7810     public boolean isFocusCycleRoot(Container container) {
7811         Container rootAncestor = getFocusCycleRootAncestor();
7812         return (rootAncestor == container);
7813     }
7814 
7815     Container getTraversalRoot() {
7816         return getFocusCycleRootAncestor();
7817     }
7818 
7819     /**
7820      * Transfers the focus to the next component, as though this Component were
7821      * the focus owner.
7822      * @see       #requestFocus()
7823      * @since     1.1
7824      */
7825     public void transferFocus() {
7826         nextFocus();
7827     }
7828 
7829     /**
7830      * @deprecated As of JDK version 1.1,
7831      * replaced by transferFocus().
7832      */
7833     @Deprecated
7834     public void nextFocus() {
7835         transferFocus(false);
7836     }
7837 
7838     boolean transferFocus(boolean clearOnFailure) {
7839         if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
7840             focusLog.finer("clearOnFailure = " + clearOnFailure);
7841         }
7842         Component toFocus = getNextFocusCandidate();
7843         boolean res = false;
7844         if (toFocus != null && !toFocus.isFocusOwner() && toFocus != this) {
7845             res = toFocus.requestFocusInWindow(CausedFocusEvent.Cause.TRAVERSAL_FORWARD);
7846         }
7847         if (clearOnFailure && !res) {
7848             if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
7849                 focusLog.finer("clear global focus owner");
7850             }
7851             KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwnerPriv();
7852         }
7853         if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
7854             focusLog.finer("returning result: " + res);
7855         }
7856         return res;
7857     }
7858 
7859     final Component getNextFocusCandidate() {
7860         Container rootAncestor = getTraversalRoot();
7861         Component comp = this;
7862         while (rootAncestor != null &&
7863                !(rootAncestor.isShowing() && rootAncestor.canBeFocusOwner()))
7864         {
7865             comp = rootAncestor;
7866             rootAncestor = comp.getFocusCycleRootAncestor();
7867         }
7868         if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
7869             focusLog.finer("comp = " + comp + ", root = " + rootAncestor);
7870         }
7871         Component candidate = null;
7872         if (rootAncestor != null) {
7873             FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy();
7874             Component toFocus = policy.getComponentAfter(rootAncestor, comp);
7875             if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
7876                 focusLog.finer("component after is " + toFocus);
7877             }
7878             if (toFocus == null) {
7879                 toFocus = policy.getDefaultComponent(rootAncestor);
7880                 if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
7881                     focusLog.finer("default component is " + toFocus);
7882                 }
7883             }
7884             if (toFocus == null) {
7885                 Applet applet = EmbeddedFrame.getAppletIfAncestorOf(this);
7886                 if (applet != null) {
7887                     toFocus = applet;
7888                 }
7889             }
7890             candidate = toFocus;
7891         }
7892         if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
7893             focusLog.finer("Focus transfer candidate: " + candidate);
7894         }
7895         return candidate;
7896     }
7897 
7898     /**
7899      * Transfers the focus to the previous component, as though this Component
7900      * were the focus owner.
7901      * @see       #requestFocus()
7902      * @since     1.4
7903      */
7904     public void transferFocusBackward() {
7905         transferFocusBackward(false);
7906     }
7907 
7908     boolean transferFocusBackward(boolean clearOnFailure) {
7909         Container rootAncestor = getTraversalRoot();
7910         Component comp = this;
7911         while (rootAncestor != null &&
7912                !(rootAncestor.isShowing() && rootAncestor.canBeFocusOwner()))
7913         {
7914             comp = rootAncestor;
7915             rootAncestor = comp.getFocusCycleRootAncestor();
7916         }
7917         boolean res = false;
7918         if (rootAncestor != null) {
7919             FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy();
7920             Component toFocus = policy.getComponentBefore(rootAncestor, comp);
7921             if (toFocus == null) {
7922                 toFocus = policy.getDefaultComponent(rootAncestor);
7923             }
7924             if (toFocus != null) {
7925                 res = toFocus.requestFocusInWindow(CausedFocusEvent.Cause.TRAVERSAL_BACKWARD);
7926             }
7927         }
7928         if (clearOnFailure && !res) {
7929             if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
7930                 focusLog.finer("clear global focus owner");
7931             }
7932             KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwnerPriv();
7933         }
7934         if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
7935             focusLog.finer("returning result: " + res);
7936         }
7937         return res;
7938     }
7939 
7940     /**
7941      * Transfers the focus up one focus traversal cycle. Typically, the focus
7942      * owner is set to this Component's focus cycle root, and the current focus
7943      * cycle root is set to the new focus owner's focus cycle root. If,
7944      * however, this Component's focus cycle root is a Window, then the focus
7945      * owner is set to the focus cycle root's default Component to focus, and
7946      * the current focus cycle root is unchanged.
7947      *
7948      * @see       #requestFocus()
7949      * @see       Container#isFocusCycleRoot()
7950      * @see       Container#setFocusCycleRoot(boolean)
7951      * @since     1.4
7952      */
7953     public void transferFocusUpCycle() {
7954         Container rootAncestor;
7955         for (rootAncestor = getFocusCycleRootAncestor();
7956              rootAncestor != null && !(rootAncestor.isShowing() &&
7957                                        rootAncestor.isFocusable() &&
7958                                        rootAncestor.isEnabled());
7959              rootAncestor = rootAncestor.getFocusCycleRootAncestor()) {
7960         }
7961 
7962         if (rootAncestor != null) {
7963             Container rootAncestorRootAncestor =
7964                 rootAncestor.getFocusCycleRootAncestor();
7965             Container fcr = (rootAncestorRootAncestor != null) ?
7966                 rootAncestorRootAncestor : rootAncestor;
7967 
7968             KeyboardFocusManager.getCurrentKeyboardFocusManager().
7969                 setGlobalCurrentFocusCycleRootPriv(fcr);
7970             rootAncestor.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_UP);
7971         } else {
7972             Window window = getContainingWindow();
7973 
7974             if (window != null) {
7975                 Component toFocus = window.getFocusTraversalPolicy().
7976                     getDefaultComponent(window);
7977                 if (toFocus != null) {
7978                     KeyboardFocusManager.getCurrentKeyboardFocusManager().
7979                         setGlobalCurrentFocusCycleRootPriv(window);
7980                     toFocus.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_UP);
7981                 }
7982             }
7983         }
7984     }
7985 
7986     /**
7987      * Returns <code>true</code> if this <code>Component</code> is the
7988      * focus owner.  This method is obsolete, and has been replaced by
7989      * <code>isFocusOwner()</code>.
7990      *
7991      * @return <code>true</code> if this <code>Component</code> is the
7992      *         focus owner; <code>false</code> otherwise
7993      * @since 1.2
7994      */
7995     public boolean hasFocus() {
7996         return (KeyboardFocusManager.getCurrentKeyboardFocusManager().
7997                 getFocusOwner() == this);
7998     }
7999 
8000     /**
8001      * Returns <code>true</code> if this <code>Component</code> is the
8002      *    focus owner.
8003      *
8004      * @return <code>true</code> if this <code>Component</code> is the
8005      *     focus owner; <code>false</code> otherwise
8006      * @since 1.4
8007      */
8008     public boolean isFocusOwner() {
8009         return hasFocus();
8010     }
8011 
8012     /*
8013      * Used to disallow auto-focus-transfer on disposal of the focus owner
8014      * in the process of disposing its parent container.
8015      */
8016     private boolean autoFocusTransferOnDisposal = true;
8017 
8018     void setAutoFocusTransferOnDisposal(boolean value) {
8019         autoFocusTransferOnDisposal = value;
8020     }
8021 
8022     boolean isAutoFocusTransferOnDisposal() {
8023         return autoFocusTransferOnDisposal;
8024     }
8025 
8026     /**
8027      * Adds the specified popup menu to the component.
8028      * @param     popup the popup menu to be added to the component.
8029      * @see       #remove(MenuComponent)
8030      * @exception NullPointerException if {@code popup} is {@code null}
8031      * @since     1.1
8032      */
8033     public void add(PopupMenu popup) {
8034         synchronized (getTreeLock()) {
8035             if (popup.parent != null) {
8036                 popup.parent.remove(popup);
8037             }
8038             if (popups == null) {
8039                 popups = new Vector<PopupMenu>();
8040             }
8041             popups.addElement(popup);
8042             popup.parent = this;
8043 
8044             if (peer != null) {
8045                 if (popup.peer == null) {
8046                     popup.addNotify();
8047                 }
8048             }
8049         }
8050     }
8051 
8052     /**
8053      * Removes the specified popup menu from the component.
8054      * @param     popup the popup menu to be removed
8055      * @see       #add(PopupMenu)
8056      * @since     1.1
8057      */
8058     @SuppressWarnings("unchecked")
8059     public void remove(MenuComponent popup) {
8060         synchronized (getTreeLock()) {
8061             if (popups == null) {
8062                 return;
8063             }
8064             int index = popups.indexOf(popup);
8065             if (index >= 0) {
8066                 PopupMenu pmenu = (PopupMenu)popup;
8067                 if (pmenu.peer != null) {
8068                     pmenu.removeNotify();
8069                 }
8070                 pmenu.parent = null;
8071                 popups.removeElementAt(index);
8072                 if (popups.size() == 0) {
8073                     popups = null;
8074                 }
8075             }
8076         }
8077     }
8078 
8079     /**
8080      * Returns a string representing the state of this component. This
8081      * method is intended to be used only for debugging purposes, and the
8082      * content and format of the returned string may vary between
8083      * implementations. The returned string may be empty but may not be
8084      * <code>null</code>.
8085      *
8086      * @return  a string representation of this component's state
8087      * @since     1.0
8088      */
8089     protected String paramString() {
8090         final String thisName = Objects.toString(getName(), "");
8091         final String invalid = isValid() ? "" : ",invalid";
8092         final String hidden = visible ? "" : ",hidden";
8093         final String disabled = enabled ? "" : ",disabled";
8094         return thisName + ',' + x + ',' + y + ',' + width + 'x' + height
8095                 + invalid + hidden + disabled;
8096     }
8097 
8098     /**
8099      * Returns a string representation of this component and its values.
8100      * @return    a string representation of this component
8101      * @since     1.0
8102      */
8103     public String toString() {
8104         return getClass().getName() + '[' + paramString() + ']';
8105     }
8106 
8107     /**
8108      * Prints a listing of this component to the standard system output
8109      * stream <code>System.out</code>.
8110      * @see       java.lang.System#out
8111      * @since     1.0
8112      */
8113     public void list() {
8114         list(System.out, 0);
8115     }
8116 
8117     /**
8118      * Prints a listing of this component to the specified output
8119      * stream.
8120      * @param    out   a print stream
8121      * @throws   NullPointerException if {@code out} is {@code null}
8122      * @since    1.0
8123      */
8124     public void list(PrintStream out) {
8125         list(out, 0);
8126     }
8127 
8128     /**
8129      * Prints out a list, starting at the specified indentation, to the
8130      * specified print stream.
8131      * @param     out      a print stream
8132      * @param     indent   number of spaces to indent
8133      * @see       java.io.PrintStream#println(java.lang.Object)
8134      * @throws    NullPointerException if {@code out} is {@code null}
8135      * @since     1.0
8136      */
8137     public void list(PrintStream out, int indent) {
8138         for (int i = 0 ; i < indent ; i++) {
8139             out.print(" ");
8140         }
8141         out.println(this);
8142     }
8143 
8144     /**
8145      * Prints a listing to the specified print writer.
8146      * @param  out  the print writer to print to
8147      * @throws NullPointerException if {@code out} is {@code null}
8148      * @since 1.1
8149      */
8150     public void list(PrintWriter out) {
8151         list(out, 0);
8152     }
8153 
8154     /**
8155      * Prints out a list, starting at the specified indentation, to
8156      * the specified print writer.
8157      * @param out the print writer to print to
8158      * @param indent the number of spaces to indent
8159      * @throws NullPointerException if {@code out} is {@code null}
8160      * @see       java.io.PrintStream#println(java.lang.Object)
8161      * @since 1.1
8162      */
8163     public void list(PrintWriter out, int indent) {
8164         for (int i = 0 ; i < indent ; i++) {
8165             out.print(" ");
8166         }
8167         out.println(this);
8168     }
8169 
8170     /*
8171      * Fetches the native container somewhere higher up in the component
8172      * tree that contains this component.
8173      */
8174     final Container getNativeContainer() {
8175         Container p = getContainer();
8176         while (p != null && p.peer instanceof LightweightPeer) {
8177             p = p.getContainer();
8178         }
8179         return p;
8180     }
8181 
8182     /**
8183      * Adds a PropertyChangeListener to the listener list. The listener is
8184      * registered for all bound properties of this class, including the
8185      * following:
8186      * <ul>
8187      *    <li>this Component's font ("font")</li>
8188      *    <li>this Component's background color ("background")</li>
8189      *    <li>this Component's foreground color ("foreground")</li>
8190      *    <li>this Component's focusability ("focusable")</li>
8191      *    <li>this Component's focus traversal keys enabled state
8192      *        ("focusTraversalKeysEnabled")</li>
8193      *    <li>this Component's Set of FORWARD_TRAVERSAL_KEYS
8194      *        ("forwardFocusTraversalKeys")</li>
8195      *    <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS
8196      *        ("backwardFocusTraversalKeys")</li>
8197      *    <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS
8198      *        ("upCycleFocusTraversalKeys")</li>
8199      *    <li>this Component's preferred size ("preferredSize")</li>
8200      *    <li>this Component's minimum size ("minimumSize")</li>
8201      *    <li>this Component's maximum size ("maximumSize")</li>
8202      *    <li>this Component's name ("name")</li>
8203      * </ul>
8204      * Note that if this <code>Component</code> is inheriting a bound property, then no
8205      * event will be fired in response to a change in the inherited property.
8206      * <p>
8207      * If <code>listener</code> is <code>null</code>,
8208      * no exception is thrown and no action is performed.
8209      *
8210      * @param    listener  the property change listener to be added
8211      *
8212      * @see #removePropertyChangeListener
8213      * @see #getPropertyChangeListeners
8214      * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8215      */
8216     public void addPropertyChangeListener(
8217                                                        PropertyChangeListener listener) {
8218         synchronized (getObjectLock()) {
8219             if (listener == null) {
8220                 return;
8221             }
8222             if (changeSupport == null) {
8223                 changeSupport = new PropertyChangeSupport(this);
8224             }
8225             changeSupport.addPropertyChangeListener(listener);
8226         }
8227     }
8228 
8229     /**
8230      * Removes a PropertyChangeListener from the listener list. This method
8231      * should be used to remove PropertyChangeListeners that were registered
8232      * for all bound properties of this class.
8233      * <p>
8234      * If listener is null, no exception is thrown and no action is performed.
8235      *
8236      * @param listener the PropertyChangeListener to be removed
8237      *
8238      * @see #addPropertyChangeListener
8239      * @see #getPropertyChangeListeners
8240      * @see #removePropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener)
8241      */
8242     public void removePropertyChangeListener(
8243                                                           PropertyChangeListener listener) {
8244         synchronized (getObjectLock()) {
8245             if (listener == null || changeSupport == null) {
8246                 return;
8247             }
8248             changeSupport.removePropertyChangeListener(listener);
8249         }
8250     }
8251 
8252     /**
8253      * Returns an array of all the property change listeners
8254      * registered on this component.
8255      *
8256      * @return all of this component's <code>PropertyChangeListener</code>s
8257      *         or an empty array if no property change
8258      *         listeners are currently registered
8259      *
8260      * @see      #addPropertyChangeListener
8261      * @see      #removePropertyChangeListener
8262      * @see      #getPropertyChangeListeners(java.lang.String)
8263      * @see      java.beans.PropertyChangeSupport#getPropertyChangeListeners
8264      * @since    1.4
8265      */
8266     public PropertyChangeListener[] getPropertyChangeListeners() {
8267         synchronized (getObjectLock()) {
8268             if (changeSupport == null) {
8269                 return new PropertyChangeListener[0];
8270             }
8271             return changeSupport.getPropertyChangeListeners();
8272         }
8273     }
8274 
8275     /**
8276      * Adds a PropertyChangeListener to the listener list for a specific
8277      * property. The specified property may be user-defined, or one of the
8278      * following:
8279      * <ul>
8280      *    <li>this Component's font ("font")</li>
8281      *    <li>this Component's background color ("background")</li>
8282      *    <li>this Component's foreground color ("foreground")</li>
8283      *    <li>this Component's focusability ("focusable")</li>
8284      *    <li>this Component's focus traversal keys enabled state
8285      *        ("focusTraversalKeysEnabled")</li>
8286      *    <li>this Component's Set of FORWARD_TRAVERSAL_KEYS
8287      *        ("forwardFocusTraversalKeys")</li>
8288      *    <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS
8289      *        ("backwardFocusTraversalKeys")</li>
8290      *    <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS
8291      *        ("upCycleFocusTraversalKeys")</li>
8292      * </ul>
8293      * Note that if this <code>Component</code> is inheriting a bound property, then no
8294      * event will be fired in response to a change in the inherited property.
8295      * <p>
8296      * If <code>propertyName</code> or <code>listener</code> is <code>null</code>,
8297      * no exception is thrown and no action is taken.
8298      *
8299      * @param propertyName one of the property names listed above
8300      * @param listener the property change listener to be added
8301      *
8302      * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8303      * @see #getPropertyChangeListeners(java.lang.String)
8304      * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8305      */
8306     public void addPropertyChangeListener(
8307                                                        String propertyName,
8308                                                        PropertyChangeListener listener) {
8309         synchronized (getObjectLock()) {
8310             if (listener == null) {
8311                 return;
8312             }
8313             if (changeSupport == null) {
8314                 changeSupport = new PropertyChangeSupport(this);
8315             }
8316             changeSupport.addPropertyChangeListener(propertyName, listener);
8317         }
8318     }
8319 
8320     /**
8321      * Removes a <code>PropertyChangeListener</code> from the listener
8322      * list for a specific property. This method should be used to remove
8323      * <code>PropertyChangeListener</code>s
8324      * that were registered for a specific bound property.
8325      * <p>
8326      * If <code>propertyName</code> or <code>listener</code> is <code>null</code>,
8327      * no exception is thrown and no action is taken.
8328      *
8329      * @param propertyName a valid property name
8330      * @param listener the PropertyChangeListener to be removed
8331      *
8332      * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8333      * @see #getPropertyChangeListeners(java.lang.String)
8334      * @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
8335      */
8336     public void removePropertyChangeListener(
8337                                                           String propertyName,
8338                                                           PropertyChangeListener listener) {
8339         synchronized (getObjectLock()) {
8340             if (listener == null || changeSupport == null) {
8341                 return;
8342             }
8343             changeSupport.removePropertyChangeListener(propertyName, listener);
8344         }
8345     }
8346 
8347     /**
8348      * Returns an array of all the listeners which have been associated
8349      * with the named property.
8350      *
8351      * @return all of the <code>PropertyChangeListener</code>s associated with
8352      *         the named property; if no such listeners have been added or
8353      *         if <code>propertyName</code> is <code>null</code>, an empty
8354      *         array is returned
8355      *
8356      * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8357      * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8358      * @see #getPropertyChangeListeners
8359      * @since 1.4
8360      */
8361     public PropertyChangeListener[] getPropertyChangeListeners(
8362                                                                             String propertyName) {
8363         synchronized (getObjectLock()) {
8364             if (changeSupport == null) {
8365                 return new PropertyChangeListener[0];
8366             }
8367             return changeSupport.getPropertyChangeListeners(propertyName);
8368         }
8369     }
8370 
8371     /**
8372      * Support for reporting bound property changes for Object properties.
8373      * This method can be called when a bound property has changed and it will
8374      * send the appropriate PropertyChangeEvent to any registered
8375      * PropertyChangeListeners.
8376      *
8377      * @param propertyName the property whose value has changed
8378      * @param oldValue the property's previous value
8379      * @param newValue the property's new value
8380      */
8381     protected void firePropertyChange(String propertyName,
8382                                       Object oldValue, Object newValue) {
8383         PropertyChangeSupport changeSupport;
8384         synchronized (getObjectLock()) {
8385             changeSupport = this.changeSupport;
8386         }
8387         if (changeSupport == null ||
8388             (oldValue != null && newValue != null && oldValue.equals(newValue))) {
8389             return;
8390         }
8391         changeSupport.firePropertyChange(propertyName, oldValue, newValue);
8392     }
8393 
8394     /**
8395      * Support for reporting bound property changes for boolean properties.
8396      * This method can be called when a bound property has changed and it will
8397      * send the appropriate PropertyChangeEvent to any registered
8398      * PropertyChangeListeners.
8399      *
8400      * @param propertyName the property whose value has changed
8401      * @param oldValue the property's previous value
8402      * @param newValue the property's new value
8403      * @since 1.4
8404      */
8405     protected void firePropertyChange(String propertyName,
8406                                       boolean oldValue, boolean newValue) {
8407         PropertyChangeSupport changeSupport = this.changeSupport;
8408         if (changeSupport == null || oldValue == newValue) {
8409             return;
8410         }
8411         changeSupport.firePropertyChange(propertyName, oldValue, newValue);
8412     }
8413 
8414     /**
8415      * Support for reporting bound property changes for integer properties.
8416      * This method can be called when a bound property has changed and it will
8417      * send the appropriate PropertyChangeEvent to any registered
8418      * PropertyChangeListeners.
8419      *
8420      * @param propertyName the property whose value has changed
8421      * @param oldValue the property's previous value
8422      * @param newValue the property's new value
8423      * @since 1.4
8424      */
8425     protected void firePropertyChange(String propertyName,
8426                                       int oldValue, int newValue) {
8427         PropertyChangeSupport changeSupport = this.changeSupport;
8428         if (changeSupport == null || oldValue == newValue) {
8429             return;
8430         }
8431         changeSupport.firePropertyChange(propertyName, oldValue, newValue);
8432     }
8433 
8434     /**
8435      * Reports a bound property change.
8436      *
8437      * @param propertyName the programmatic name of the property
8438      *          that was changed
8439      * @param oldValue the old value of the property (as a byte)
8440      * @param newValue the new value of the property (as a byte)
8441      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8442      *          java.lang.Object)
8443      * @since 1.5
8444      */
8445     public void firePropertyChange(String propertyName, byte oldValue, byte newValue) {
8446         if (changeSupport == null || oldValue == newValue) {
8447             return;
8448         }
8449         firePropertyChange(propertyName, Byte.valueOf(oldValue), Byte.valueOf(newValue));
8450     }
8451 
8452     /**
8453      * Reports a bound property change.
8454      *
8455      * @param propertyName the programmatic name of the property
8456      *          that was changed
8457      * @param oldValue the old value of the property (as a char)
8458      * @param newValue the new value of the property (as a char)
8459      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8460      *          java.lang.Object)
8461      * @since 1.5
8462      */
8463     public void firePropertyChange(String propertyName, char oldValue, char newValue) {
8464         if (changeSupport == null || oldValue == newValue) {
8465             return;
8466         }
8467         firePropertyChange(propertyName, new Character(oldValue), new Character(newValue));
8468     }
8469 
8470     /**
8471      * Reports a bound property change.
8472      *
8473      * @param propertyName the programmatic name of the property
8474      *          that was changed
8475      * @param oldValue the old value of the property (as a short)
8476      * @param newValue the old value of the property (as a short)
8477      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8478      *          java.lang.Object)
8479      * @since 1.5
8480      */
8481     public void firePropertyChange(String propertyName, short oldValue, short newValue) {
8482         if (changeSupport == null || oldValue == newValue) {
8483             return;
8484         }
8485         firePropertyChange(propertyName, Short.valueOf(oldValue), Short.valueOf(newValue));
8486     }
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 long)
8495      * @param newValue the new value of the property (as a long)
8496      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8497      *          java.lang.Object)
8498      * @since 1.5
8499      */
8500     public void firePropertyChange(String propertyName, long oldValue, long newValue) {
8501         if (changeSupport == null || oldValue == newValue) {
8502             return;
8503         }
8504         firePropertyChange(propertyName, Long.valueOf(oldValue), Long.valueOf(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 float)
8513      * @param newValue the new value of the property (as a float)
8514      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8515      *          java.lang.Object)
8516      * @since 1.5
8517      */
8518     public void firePropertyChange(String propertyName, float oldValue, float newValue) {
8519         if (changeSupport == null || oldValue == newValue) {
8520             return;
8521         }
8522         firePropertyChange(propertyName, Float.valueOf(oldValue), Float.valueOf(newValue));
8523     }
8524 
8525     /**
8526      * Reports a bound property change.
8527      *
8528      * @param propertyName the programmatic name of the property
8529      *          that was changed
8530      * @param oldValue the old value of the property (as a double)
8531      * @param newValue the new value of the property (as a double)
8532      * @see #firePropertyChange(java.lang.String, java.lang.Object,
8533      *          java.lang.Object)
8534      * @since 1.5
8535      */
8536     public void firePropertyChange(String propertyName, double oldValue, double newValue) {
8537         if (changeSupport == null || oldValue == newValue) {
8538             return;
8539         }
8540         firePropertyChange(propertyName, Double.valueOf(oldValue), Double.valueOf(newValue));
8541     }
8542 
8543 
8544     // Serialization support.
8545 
8546     /**
8547      * Component Serialized Data Version.
8548      *
8549      * @serial
8550      */
8551     private int componentSerializedDataVersion = 4;
8552 
8553     /**
8554      * This hack is for Swing serialization. It will invoke
8555      * the Swing package private method <code>compWriteObjectNotify</code>.
8556      */
8557     private void doSwingSerialization() {
8558         Package swingPackage = Package.getPackage("javax.swing");
8559         // For Swing serialization to correctly work Swing needs to
8560         // be notified before Component does it's serialization.  This
8561         // hack accomodates this.
8562         //
8563         // Swing classes MUST be loaded by the bootstrap class loader,
8564         // otherwise we don't consider them.
8565         for (Class<?> klass = Component.this.getClass(); klass != null;
8566                    klass = klass.getSuperclass()) {
8567             if (klass.getPackage() == swingPackage &&
8568                       klass.getClassLoader() == null) {
8569                 final Class<?> swingClass = klass;
8570                 // Find the first override of the compWriteObjectNotify method
8571                 Method[] methods = AccessController.doPrivileged(
8572                                                                  new PrivilegedAction<Method[]>() {
8573                                                                      public Method[] run() {
8574                                                                          return swingClass.getDeclaredMethods();
8575                                                                      }
8576                                                                  });
8577                 for (int counter = methods.length - 1; counter >= 0;
8578                      counter--) {
8579                     final Method method = methods[counter];
8580                     if (method.getName().equals("compWriteObjectNotify")){
8581                         // We found it, use doPrivileged to make it accessible
8582                         // to use.
8583                         AccessController.doPrivileged(new PrivilegedAction<Void>() {
8584                                 public Void run() {
8585                                     method.setAccessible(true);
8586                                     return null;
8587                                 }
8588                             });
8589                         // Invoke the method
8590                         try {
8591                             method.invoke(this, (Object[]) null);
8592                         } catch (IllegalAccessException iae) {
8593                         } catch (InvocationTargetException ite) {
8594                         }
8595                         // We're done, bail.
8596                         return;
8597                     }
8598                 }
8599             }
8600         }
8601     }
8602 
8603     /**
8604      * Writes default serializable fields to stream.  Writes
8605      * a variety of serializable listeners as optional data.
8606      * The non-serializable listeners are detected and
8607      * no attempt is made to serialize them.
8608      *
8609      * @param s the <code>ObjectOutputStream</code> to write
8610      * @serialData <code>null</code> terminated sequence of
8611      *   0 or more pairs; the pair consists of a <code>String</code>
8612      *   and an <code>Object</code>; the <code>String</code> indicates
8613      *   the type of object and is one of the following (as of 1.4):
8614      *   <code>componentListenerK</code> indicating an
8615      *     <code>ComponentListener</code> object;
8616      *   <code>focusListenerK</code> indicating an
8617      *     <code>FocusListener</code> object;
8618      *   <code>keyListenerK</code> indicating an
8619      *     <code>KeyListener</code> object;
8620      *   <code>mouseListenerK</code> indicating an
8621      *     <code>MouseListener</code> object;
8622      *   <code>mouseMotionListenerK</code> indicating an
8623      *     <code>MouseMotionListener</code> object;
8624      *   <code>inputMethodListenerK</code> indicating an
8625      *     <code>InputMethodListener</code> object;
8626      *   <code>hierarchyListenerK</code> indicating an
8627      *     <code>HierarchyListener</code> object;
8628      *   <code>hierarchyBoundsListenerK</code> indicating an
8629      *     <code>HierarchyBoundsListener</code> object;
8630      *   <code>mouseWheelListenerK</code> indicating an
8631      *     <code>MouseWheelListener</code> object
8632      * @serialData an optional <code>ComponentOrientation</code>
8633      *    (after <code>inputMethodListener</code>, as of 1.2)
8634      *
8635      * @see AWTEventMulticaster#save(java.io.ObjectOutputStream, java.lang.String, java.util.EventListener)
8636      * @see #componentListenerK
8637      * @see #focusListenerK
8638      * @see #keyListenerK
8639      * @see #mouseListenerK
8640      * @see #mouseMotionListenerK
8641      * @see #inputMethodListenerK
8642      * @see #hierarchyListenerK
8643      * @see #hierarchyBoundsListenerK
8644      * @see #mouseWheelListenerK
8645      * @see #readObject(ObjectInputStream)
8646      */
8647     private void writeObject(ObjectOutputStream s)
8648       throws IOException
8649     {
8650         doSwingSerialization();
8651 
8652         s.defaultWriteObject();
8653 
8654         AWTEventMulticaster.save(s, componentListenerK, componentListener);
8655         AWTEventMulticaster.save(s, focusListenerK, focusListener);
8656         AWTEventMulticaster.save(s, keyListenerK, keyListener);
8657         AWTEventMulticaster.save(s, mouseListenerK, mouseListener);
8658         AWTEventMulticaster.save(s, mouseMotionListenerK, mouseMotionListener);
8659         AWTEventMulticaster.save(s, inputMethodListenerK, inputMethodListener);
8660 
8661         s.writeObject(null);
8662         s.writeObject(componentOrientation);
8663 
8664         AWTEventMulticaster.save(s, hierarchyListenerK, hierarchyListener);
8665         AWTEventMulticaster.save(s, hierarchyBoundsListenerK,
8666                                  hierarchyBoundsListener);
8667         s.writeObject(null);
8668 
8669         AWTEventMulticaster.save(s, mouseWheelListenerK, mouseWheelListener);
8670         s.writeObject(null);
8671 
8672     }
8673 
8674     /**
8675      * Reads the <code>ObjectInputStream</code> and if it isn't
8676      * <code>null</code> adds a listener to receive a variety
8677      * of events fired by the component.
8678      * Unrecognized keys or values will be ignored.
8679      *
8680      * @param s the <code>ObjectInputStream</code> to read
8681      * @see #writeObject(ObjectOutputStream)
8682      */
8683     private void readObject(ObjectInputStream s)
8684       throws ClassNotFoundException, IOException
8685     {
8686         objectLock = new Object();
8687 
8688         acc = AccessController.getContext();
8689 
8690         s.defaultReadObject();
8691 
8692         appContext = AppContext.getAppContext();
8693         coalescingEnabled = checkCoalescing();
8694         if (componentSerializedDataVersion < 4) {
8695             // These fields are non-transient and rely on default
8696             // serialization. However, the default values are insufficient,
8697             // so we need to set them explicitly for object data streams prior
8698             // to 1.4.
8699             focusable = true;
8700             isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN;
8701             initializeFocusTraversalKeys();
8702             focusTraversalKeysEnabled = true;
8703         }
8704 
8705         Object keyOrNull;
8706         while(null != (keyOrNull = s.readObject())) {
8707             String key = ((String)keyOrNull).intern();
8708 
8709             if (componentListenerK == key)
8710                 addComponentListener((ComponentListener)(s.readObject()));
8711 
8712             else if (focusListenerK == key)
8713                 addFocusListener((FocusListener)(s.readObject()));
8714 
8715             else if (keyListenerK == key)
8716                 addKeyListener((KeyListener)(s.readObject()));
8717 
8718             else if (mouseListenerK == key)
8719                 addMouseListener((MouseListener)(s.readObject()));
8720 
8721             else if (mouseMotionListenerK == key)
8722                 addMouseMotionListener((MouseMotionListener)(s.readObject()));
8723 
8724             else if (inputMethodListenerK == key)
8725                 addInputMethodListener((InputMethodListener)(s.readObject()));
8726 
8727             else // skip value for unrecognized key
8728                 s.readObject();
8729 
8730         }
8731 
8732         // Read the component's orientation if it's present
8733         Object orient = null;
8734 
8735         try {
8736             orient = s.readObject();
8737         } catch (java.io.OptionalDataException e) {
8738             // JDK 1.1 instances will not have this optional data.
8739             // e.eof will be true to indicate that there is no more
8740             // data available for this object.
8741             // If e.eof is not true, throw the exception as it
8742             // might have been caused by reasons unrelated to
8743             // componentOrientation.
8744 
8745             if (!e.eof)  {
8746                 throw (e);
8747             }
8748         }
8749 
8750         if (orient != null) {
8751             componentOrientation = (ComponentOrientation)orient;
8752         } else {
8753             componentOrientation = ComponentOrientation.UNKNOWN;
8754         }
8755 
8756         try {
8757             while(null != (keyOrNull = s.readObject())) {
8758                 String key = ((String)keyOrNull).intern();
8759 
8760                 if (hierarchyListenerK == key) {
8761                     addHierarchyListener((HierarchyListener)(s.readObject()));
8762                 }
8763                 else if (hierarchyBoundsListenerK == key) {
8764                     addHierarchyBoundsListener((HierarchyBoundsListener)
8765                                                (s.readObject()));
8766                 }
8767                 else {
8768                     // skip value for unrecognized key
8769                     s.readObject();
8770                 }
8771             }
8772         } catch (java.io.OptionalDataException e) {
8773             // JDK 1.1/1.2 instances will not have this optional data.
8774             // e.eof will be true to indicate that there is no more
8775             // data available for this object.
8776             // If e.eof is not true, throw the exception as it
8777             // might have been caused by reasons unrelated to
8778             // hierarchy and hierarchyBounds listeners.
8779 
8780             if (!e.eof)  {
8781                 throw (e);
8782             }
8783         }
8784 
8785         try {
8786             while (null != (keyOrNull = s.readObject())) {
8787                 String key = ((String)keyOrNull).intern();
8788 
8789                 if (mouseWheelListenerK == key) {
8790                     addMouseWheelListener((MouseWheelListener)(s.readObject()));
8791                 }
8792                 else {
8793                     // skip value for unrecognized key
8794                     s.readObject();
8795                 }
8796             }
8797         } catch (java.io.OptionalDataException e) {
8798             // pre-1.3 instances will not have this optional data.
8799             // e.eof will be true to indicate that there is no more
8800             // data available for this object.
8801             // If e.eof is not true, throw the exception as it
8802             // might have been caused by reasons unrelated to
8803             // mouse wheel listeners
8804 
8805             if (!e.eof)  {
8806                 throw (e);
8807             }
8808         }
8809 
8810         if (popups != null) {
8811             int npopups = popups.size();
8812             for (int i = 0 ; i < npopups ; i++) {
8813                 PopupMenu popup = popups.elementAt(i);
8814                 popup.parent = this;
8815             }
8816         }
8817     }
8818 
8819     /**
8820      * Sets the language-sensitive orientation that is to be used to order
8821      * the elements or text within this component.  Language-sensitive
8822      * <code>LayoutManager</code> and <code>Component</code>
8823      * subclasses will use this property to
8824      * determine how to lay out and draw components.
8825      * <p>
8826      * At construction time, a component's orientation is set to
8827      * <code>ComponentOrientation.UNKNOWN</code>,
8828      * indicating that it has not been specified
8829      * explicitly.  The UNKNOWN orientation behaves the same as
8830      * <code>ComponentOrientation.LEFT_TO_RIGHT</code>.
8831      * <p>
8832      * To set the orientation of a single component, use this method.
8833      * To set the orientation of an entire component
8834      * hierarchy, use
8835      * {@link #applyComponentOrientation applyComponentOrientation}.
8836      * <p>
8837      * This method changes layout-related information, and therefore,
8838      * invalidates the component hierarchy.
8839      *
8840      *
8841      * @see ComponentOrientation
8842      * @see #invalidate
8843      *
8844      * @author Laura Werner, IBM
8845      * @beaninfo
8846      *       bound: true
8847      */
8848     public void setComponentOrientation(ComponentOrientation o) {
8849         ComponentOrientation oldValue = componentOrientation;
8850         componentOrientation = o;
8851 
8852         // This is a bound property, so report the change to
8853         // any registered listeners.  (Cheap if there are none.)
8854         firePropertyChange("componentOrientation", oldValue, o);
8855 
8856         // This could change the preferred size of the Component.
8857         invalidateIfValid();
8858     }
8859 
8860     /**
8861      * Retrieves the language-sensitive orientation that is to be used to order
8862      * the elements or text within this component.  <code>LayoutManager</code>
8863      * and <code>Component</code>
8864      * subclasses that wish to respect orientation should call this method to
8865      * get the component's orientation before performing layout or drawing.
8866      *
8867      * @see ComponentOrientation
8868      *
8869      * @author Laura Werner, IBM
8870      */
8871     public ComponentOrientation getComponentOrientation() {
8872         return componentOrientation;
8873     }
8874 
8875     /**
8876      * Sets the <code>ComponentOrientation</code> property of this component
8877      * and all components contained within it.
8878      * <p>
8879      * This method changes layout-related information, and therefore,
8880      * invalidates the component hierarchy.
8881      *
8882      *
8883      * @param orientation the new component orientation of this component and
8884      *        the components contained within it.
8885      * @exception NullPointerException if <code>orientation</code> is null.
8886      * @see #setComponentOrientation
8887      * @see #getComponentOrientation
8888      * @see #invalidate
8889      * @since 1.4
8890      */
8891     public void applyComponentOrientation(ComponentOrientation orientation) {
8892         if (orientation == null) {
8893             throw new NullPointerException();
8894         }
8895         setComponentOrientation(orientation);
8896     }
8897 
8898     final boolean canBeFocusOwner() {
8899         // It is enabled, visible, focusable.
8900         if (isEnabled() && isDisplayable() && isVisible() && isFocusable()) {
8901             return true;
8902         }
8903         return false;
8904     }
8905 
8906     /**
8907      * Checks that this component meets the prerequesites to be focus owner:
8908      * - it is enabled, visible, focusable
8909      * - it's parents are all enabled and showing
8910      * - top-level window is focusable
8911      * - if focus cycle root has DefaultFocusTraversalPolicy then it also checks that this policy accepts
8912      * this component as focus owner
8913      * @since 1.5
8914      */
8915     final boolean canBeFocusOwnerRecursively() {
8916         // - it is enabled, visible, focusable
8917         if (!canBeFocusOwner()) {
8918             return false;
8919         }
8920 
8921         // - it's parents are all enabled and showing
8922         synchronized(getTreeLock()) {
8923             if (parent != null) {
8924                 return parent.canContainFocusOwner(this);
8925             }
8926         }
8927         return true;
8928     }
8929 
8930     /**
8931      * Fix the location of the HW component in a LW container hierarchy.
8932      */
8933     final void relocateComponent() {
8934         synchronized (getTreeLock()) {
8935             if (peer == null) {
8936                 return;
8937             }
8938             int nativeX = x;
8939             int nativeY = y;
8940             for (Component cont = getContainer();
8941                     cont != null && cont.isLightweight();
8942                     cont = cont.getContainer())
8943             {
8944                 nativeX += cont.x;
8945                 nativeY += cont.y;
8946             }
8947             peer.setBounds(nativeX, nativeY, width, height,
8948                     ComponentPeer.SET_LOCATION);
8949         }
8950     }
8951 
8952     /**
8953      * Returns the <code>Window</code> ancestor of the component.
8954      * @return Window ancestor of the component or component by itself if it is Window;
8955      *         null, if component is not a part of window hierarchy
8956      */
8957     Window getContainingWindow() {
8958         return SunToolkit.getContainingWindow(this);
8959     }
8960 
8961     /**
8962      * Initialize JNI field and method IDs
8963      */
8964     private static native void initIDs();
8965 
8966     /*
8967      * --- Accessibility Support ---
8968      *
8969      *  Component will contain all of the methods in interface Accessible,
8970      *  though it won't actually implement the interface - that will be up
8971      *  to the individual objects which extend Component.
8972      */
8973 
8974     /**
8975      * The {@code AccessibleContext} associated with this {@code Component}.
8976      */
8977     protected AccessibleContext accessibleContext = null;
8978 
8979     /**
8980      * Gets the <code>AccessibleContext</code> associated
8981      * with this <code>Component</code>.
8982      * The method implemented by this base
8983      * class returns null.  Classes that extend <code>Component</code>
8984      * should implement this method to return the
8985      * <code>AccessibleContext</code> associated with the subclass.
8986      *
8987      *
8988      * @return the <code>AccessibleContext</code> of this
8989      *    <code>Component</code>
8990      * @since 1.3
8991      */
8992     public AccessibleContext getAccessibleContext() {
8993         return accessibleContext;
8994     }
8995 
8996     /**
8997      * Inner class of Component used to provide default support for
8998      * accessibility.  This class is not meant to be used directly by
8999      * application developers, but is instead meant only to be
9000      * subclassed by component developers.
9001      * <p>
9002      * The class used to obtain the accessible role for this object.
9003      * @since 1.3
9004      */
9005     protected abstract class AccessibleAWTComponent extends AccessibleContext
9006         implements Serializable, AccessibleComponent {
9007 
9008         private static final long serialVersionUID = 642321655757800191L;
9009 
9010         /**
9011          * Though the class is abstract, this should be called by
9012          * all sub-classes.
9013          */
9014         protected AccessibleAWTComponent() {
9015         }
9016 
9017         /**
9018          * Number of PropertyChangeListener objects registered. It's used
9019          * to add/remove ComponentListener and FocusListener to track
9020          * target Component's state.
9021          */
9022         private volatile transient int propertyListenersCount = 0;
9023 
9024         protected ComponentListener accessibleAWTComponentHandler = null;
9025         protected FocusListener accessibleAWTFocusHandler = null;
9026 
9027         /**
9028          * Fire PropertyChange listener, if one is registered,
9029          * when shown/hidden..
9030          * @since 1.3
9031          */
9032         protected class AccessibleAWTComponentHandler implements ComponentListener {
9033             public void componentHidden(ComponentEvent e)  {
9034                 if (accessibleContext != null) {
9035                     accessibleContext.firePropertyChange(
9036                                                          AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9037                                                          AccessibleState.VISIBLE, null);
9038                 }
9039             }
9040 
9041             public void componentShown(ComponentEvent e)  {
9042                 if (accessibleContext != null) {
9043                     accessibleContext.firePropertyChange(
9044                                                          AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9045                                                          null, AccessibleState.VISIBLE);
9046                 }
9047             }
9048 
9049             public void componentMoved(ComponentEvent e)  {
9050             }
9051 
9052             public void componentResized(ComponentEvent e)  {
9053             }
9054         } // inner class AccessibleAWTComponentHandler
9055 
9056 
9057         /**
9058          * Fire PropertyChange listener, if one is registered,
9059          * when focus events happen
9060          * @since 1.3
9061          */
9062         protected class AccessibleAWTFocusHandler implements FocusListener {
9063             public void focusGained(FocusEvent event) {
9064                 if (accessibleContext != null) {
9065                     accessibleContext.firePropertyChange(
9066                                                          AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9067                                                          null, AccessibleState.FOCUSED);
9068                 }
9069             }
9070             public void focusLost(FocusEvent event) {
9071                 if (accessibleContext != null) {
9072                     accessibleContext.firePropertyChange(
9073                                                          AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9074                                                          AccessibleState.FOCUSED, null);
9075                 }
9076             }
9077         }  // inner class AccessibleAWTFocusHandler
9078 
9079 
9080         /**
9081          * Adds a <code>PropertyChangeListener</code> to the listener list.
9082          *
9083          * @param listener  the property change listener to be added
9084          */
9085         public void addPropertyChangeListener(PropertyChangeListener listener) {
9086             if (accessibleAWTComponentHandler == null) {
9087                 accessibleAWTComponentHandler = new AccessibleAWTComponentHandler();
9088             }
9089             if (accessibleAWTFocusHandler == null) {
9090                 accessibleAWTFocusHandler = new AccessibleAWTFocusHandler();
9091             }
9092             if (propertyListenersCount++ == 0) {
9093                 Component.this.addComponentListener(accessibleAWTComponentHandler);
9094                 Component.this.addFocusListener(accessibleAWTFocusHandler);
9095             }
9096             super.addPropertyChangeListener(listener);
9097         }
9098 
9099         /**
9100          * Remove a PropertyChangeListener from the listener list.
9101          * This removes a PropertyChangeListener that was registered
9102          * for all properties.
9103          *
9104          * @param listener  The PropertyChangeListener to be removed
9105          */
9106         public void removePropertyChangeListener(PropertyChangeListener listener) {
9107             if (--propertyListenersCount == 0) {
9108                 Component.this.removeComponentListener(accessibleAWTComponentHandler);
9109                 Component.this.removeFocusListener(accessibleAWTFocusHandler);
9110             }
9111             super.removePropertyChangeListener(listener);
9112         }
9113 
9114         // AccessibleContext methods
9115         //
9116         /**
9117          * Gets the accessible name of this object.  This should almost never
9118          * return <code>java.awt.Component.getName()</code>,
9119          * as that generally isn't a localized name,
9120          * and doesn't have meaning for the user.  If the
9121          * object is fundamentally a text object (e.g. a menu item), the
9122          * accessible name should be the text of the object (e.g. "save").
9123          * If the object has a tooltip, the tooltip text may also be an
9124          * appropriate String to return.
9125          *
9126          * @return the localized name of the object -- can be
9127          *         <code>null</code> if this
9128          *         object does not have a name
9129          * @see javax.accessibility.AccessibleContext#setAccessibleName
9130          */
9131         public String getAccessibleName() {
9132             return accessibleName;
9133         }
9134 
9135         /**
9136          * Gets the accessible description of this object.  This should be
9137          * a concise, localized description of what this object is - what
9138          * is its meaning to the user.  If the object has a tooltip, the
9139          * tooltip text may be an appropriate string to return, assuming
9140          * it contains a concise description of the object (instead of just
9141          * the name of the object - e.g. a "Save" icon on a toolbar that
9142          * had "save" as the tooltip text shouldn't return the tooltip
9143          * text as the description, but something like "Saves the current
9144          * text document" instead).
9145          *
9146          * @return the localized description of the object -- can be
9147          *        <code>null</code> if this object does not have a description
9148          * @see javax.accessibility.AccessibleContext#setAccessibleDescription
9149          */
9150         public String getAccessibleDescription() {
9151             return accessibleDescription;
9152         }
9153 
9154         /**
9155          * Gets the role of this object.
9156          *
9157          * @return an instance of <code>AccessibleRole</code>
9158          *      describing the role of the object
9159          * @see javax.accessibility.AccessibleRole
9160          */
9161         public AccessibleRole getAccessibleRole() {
9162             return AccessibleRole.AWT_COMPONENT;
9163         }
9164 
9165         /**
9166          * Gets the state of this object.
9167          *
9168          * @return an instance of <code>AccessibleStateSet</code>
9169          *       containing the current state set of the object
9170          * @see javax.accessibility.AccessibleState
9171          */
9172         public AccessibleStateSet getAccessibleStateSet() {
9173             return Component.this.getAccessibleStateSet();
9174         }
9175 
9176         /**
9177          * Gets the <code>Accessible</code> parent of this object.
9178          * If the parent of this object implements <code>Accessible</code>,
9179          * this method should simply return <code>getParent</code>.
9180          *
9181          * @return the <code>Accessible</code> parent of this
9182          *      object -- can be <code>null</code> if this
9183          *      object does not have an <code>Accessible</code> parent
9184          */
9185         public Accessible getAccessibleParent() {
9186             if (accessibleParent != null) {
9187                 return accessibleParent;
9188             } else {
9189                 Container parent = getParent();
9190                 if (parent instanceof Accessible) {
9191                     return (Accessible) parent;
9192                 }
9193             }
9194             return null;
9195         }
9196 
9197         /**
9198          * Gets the index of this object in its accessible parent.
9199          *
9200          * @return the index of this object in its parent; or -1 if this
9201          *    object does not have an accessible parent
9202          * @see #getAccessibleParent
9203          */
9204         public int getAccessibleIndexInParent() {
9205             return Component.this.getAccessibleIndexInParent();
9206         }
9207 
9208         /**
9209          * Returns the number of accessible children in the object.  If all
9210          * of the children of this object implement <code>Accessible</code>,
9211          * then this method should return the number of children of this object.
9212          *
9213          * @return the number of accessible children in the object
9214          */
9215         public int getAccessibleChildrenCount() {
9216             return 0; // Components don't have children
9217         }
9218 
9219         /**
9220          * Returns the nth <code>Accessible</code> child of the object.
9221          *
9222          * @param i zero-based index of child
9223          * @return the nth <code>Accessible</code> child of the object
9224          */
9225         public Accessible getAccessibleChild(int i) {
9226             return null; // Components don't have children
9227         }
9228 
9229         /**
9230          * Returns the locale of this object.
9231          *
9232          * @return the locale of this object
9233          */
9234         public Locale getLocale() {
9235             return Component.this.getLocale();
9236         }
9237 
9238         /**
9239          * Gets the <code>AccessibleComponent</code> associated
9240          * with this object if one exists.
9241          * Otherwise return <code>null</code>.
9242          *
9243          * @return the component
9244          */
9245         public AccessibleComponent getAccessibleComponent() {
9246             return this;
9247         }
9248 
9249 
9250         // AccessibleComponent methods
9251         //
9252         /**
9253          * Gets the background color of this object.
9254          *
9255          * @return the background color, if supported, of the object;
9256          *      otherwise, <code>null</code>
9257          */
9258         public Color getBackground() {
9259             return Component.this.getBackground();
9260         }
9261 
9262         /**
9263          * Sets the background color of this object.
9264          * (For transparency, see <code>isOpaque</code>.)
9265          *
9266          * @param c the new <code>Color</code> for the background
9267          * @see Component#isOpaque
9268          */
9269         public void setBackground(Color c) {
9270             Component.this.setBackground(c);
9271         }
9272 
9273         /**
9274          * Gets the foreground color of this object.
9275          *
9276          * @return the foreground color, if supported, of the object;
9277          *     otherwise, <code>null</code>
9278          */
9279         public Color getForeground() {
9280             return Component.this.getForeground();
9281         }
9282 
9283         /**
9284          * Sets the foreground color of this object.
9285          *
9286          * @param c the new <code>Color</code> for the foreground
9287          */
9288         public void setForeground(Color c) {
9289             Component.this.setForeground(c);
9290         }
9291 
9292         /**
9293          * Gets the <code>Cursor</code> of this object.
9294          *
9295          * @return the <code>Cursor</code>, if supported,
9296          *     of the object; otherwise, <code>null</code>
9297          */
9298         public Cursor getCursor() {
9299             return Component.this.getCursor();
9300         }
9301 
9302         /**
9303          * Sets the <code>Cursor</code> of this object.
9304          * <p>
9305          * The method may have no visual effect if the Java platform
9306          * implementation and/or the native system do not support
9307          * changing the mouse cursor shape.
9308          * @param cursor the new <code>Cursor</code> for the object
9309          */
9310         public void setCursor(Cursor cursor) {
9311             Component.this.setCursor(cursor);
9312         }
9313 
9314         /**
9315          * Gets the <code>Font</code> of this object.
9316          *
9317          * @return the <code>Font</code>, if supported,
9318          *    for the object; otherwise, <code>null</code>
9319          */
9320         public Font getFont() {
9321             return Component.this.getFont();
9322         }
9323 
9324         /**
9325          * Sets the <code>Font</code> of this object.
9326          *
9327          * @param f the new <code>Font</code> for the object
9328          */
9329         public void setFont(Font f) {
9330             Component.this.setFont(f);
9331         }
9332 
9333         /**
9334          * Gets the <code>FontMetrics</code> of this object.
9335          *
9336          * @param f the <code>Font</code>
9337          * @return the <code>FontMetrics</code>, if supported,
9338          *     the object; otherwise, <code>null</code>
9339          * @see #getFont
9340          */
9341         public FontMetrics getFontMetrics(Font f) {
9342             if (f == null) {
9343                 return null;
9344             } else {
9345                 return Component.this.getFontMetrics(f);
9346             }
9347         }
9348 
9349         /**
9350          * Determines if the object is enabled.
9351          *
9352          * @return true if object is enabled; otherwise, false
9353          */
9354         public boolean isEnabled() {
9355             return Component.this.isEnabled();
9356         }
9357 
9358         /**
9359          * Sets the enabled state of the object.
9360          *
9361          * @param b if true, enables this object; otherwise, disables it
9362          */
9363         public void setEnabled(boolean b) {
9364             boolean old = Component.this.isEnabled();
9365             Component.this.setEnabled(b);
9366             if (b != old) {
9367                 if (accessibleContext != null) {
9368                     if (b) {
9369                         accessibleContext.firePropertyChange(
9370                                                              AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9371                                                              null, AccessibleState.ENABLED);
9372                     } else {
9373                         accessibleContext.firePropertyChange(
9374                                                              AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9375                                                              AccessibleState.ENABLED, null);
9376                     }
9377                 }
9378             }
9379         }
9380 
9381         /**
9382          * Determines if the object is visible.  Note: this means that the
9383          * object intends to be visible; however, it may not in fact be
9384          * showing on the screen because one of the objects that this object
9385          * is contained by is not visible.  To determine if an object is
9386          * showing on the screen, use <code>isShowing</code>.
9387          *
9388          * @return true if object is visible; otherwise, false
9389          */
9390         public boolean isVisible() {
9391             return Component.this.isVisible();
9392         }
9393 
9394         /**
9395          * Sets the visible state of the object.
9396          *
9397          * @param b if true, shows this object; otherwise, hides it
9398          */
9399         public void setVisible(boolean b) {
9400             boolean old = Component.this.isVisible();
9401             Component.this.setVisible(b);
9402             if (b != old) {
9403                 if (accessibleContext != null) {
9404                     if (b) {
9405                         accessibleContext.firePropertyChange(
9406                                                              AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9407                                                              null, AccessibleState.VISIBLE);
9408                     } else {
9409                         accessibleContext.firePropertyChange(
9410                                                              AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9411                                                              AccessibleState.VISIBLE, null);
9412                     }
9413                 }
9414             }
9415         }
9416 
9417         /**
9418          * Determines if the object is showing.  This is determined by checking
9419          * the visibility of the object and ancestors of the object.  Note:
9420          * this will return true even if the object is obscured by another
9421          * (for example, it happens to be underneath a menu that was pulled
9422          * down).
9423          *
9424          * @return true if object is showing; otherwise, false
9425          */
9426         public boolean isShowing() {
9427             return Component.this.isShowing();
9428         }
9429 
9430         /**
9431          * Checks whether the specified point is within this object's bounds,
9432          * where the point's x and y coordinates are defined to be relative to
9433          * the coordinate system of the object.
9434          *
9435          * @param p the <code>Point</code> relative to the
9436          *     coordinate system of the object
9437          * @return true if object contains <code>Point</code>; otherwise false
9438          */
9439         public boolean contains(Point p) {
9440             return Component.this.contains(p);
9441         }
9442 
9443         /**
9444          * Returns the location of the object on the screen.
9445          *
9446          * @return location of object on screen -- can be
9447          *    <code>null</code> if this object is not on the screen
9448          */
9449         public Point getLocationOnScreen() {
9450             synchronized (Component.this.getTreeLock()) {
9451                 if (Component.this.isShowing()) {
9452                     return Component.this.getLocationOnScreen();
9453                 } else {
9454                     return null;
9455                 }
9456             }
9457         }
9458 
9459         /**
9460          * Gets the location of the object relative to the parent in the form
9461          * of a point specifying the object's top-left corner in the screen's
9462          * coordinate space.
9463          *
9464          * @return an instance of Point representing the top-left corner of
9465          * the object's bounds in the coordinate space of the screen;
9466          * <code>null</code> if this object or its parent are not on the screen
9467          */
9468         public Point getLocation() {
9469             return Component.this.getLocation();
9470         }
9471 
9472         /**
9473          * Sets the location of the object relative to the parent.
9474          * @param p  the coordinates of the object
9475          */
9476         public void setLocation(Point p) {
9477             Component.this.setLocation(p);
9478         }
9479 
9480         /**
9481          * Gets the bounds of this object in the form of a Rectangle object.
9482          * The bounds specify this object's width, height, and location
9483          * relative to its parent.
9484          *
9485          * @return a rectangle indicating this component's bounds;
9486          *   <code>null</code> if this object is not on the screen
9487          */
9488         public Rectangle getBounds() {
9489             return Component.this.getBounds();
9490         }
9491 
9492         /**
9493          * Sets the bounds of this object in the form of a
9494          * <code>Rectangle</code> object.
9495          * The bounds specify this object's width, height, and location
9496          * relative to its parent.
9497          *
9498          * @param r a rectangle indicating this component's bounds
9499          */
9500         public void setBounds(Rectangle r) {
9501             Component.this.setBounds(r);
9502         }
9503 
9504         /**
9505          * Returns the size of this object in the form of a
9506          * <code>Dimension</code> object. The height field of the
9507          * <code>Dimension</code> object contains this objects's
9508          * height, and the width field of the <code>Dimension</code>
9509          * object contains this object's width.
9510          *
9511          * @return a <code>Dimension</code> object that indicates
9512          *     the size of this component; <code>null</code> if
9513          *     this object is not on the screen
9514          */
9515         public Dimension getSize() {
9516             return Component.this.getSize();
9517         }
9518 
9519         /**
9520          * Resizes this object so that it has width and height.
9521          *
9522          * @param d - the dimension specifying the new size of the object
9523          */
9524         public void setSize(Dimension d) {
9525             Component.this.setSize(d);
9526         }
9527 
9528         /**
9529          * Returns the <code>Accessible</code> child,
9530          * if one exists, contained at the local
9531          * coordinate <code>Point</code>.  Otherwise returns
9532          * <code>null</code>.
9533          *
9534          * @param p the point defining the top-left corner of
9535          *      the <code>Accessible</code>, given in the
9536          *      coordinate space of the object's parent
9537          * @return the <code>Accessible</code>, if it exists,
9538          *      at the specified location; else <code>null</code>
9539          */
9540         public Accessible getAccessibleAt(Point p) {
9541             return null; // Components don't have children
9542         }
9543 
9544         /**
9545          * Returns whether this object can accept focus or not.
9546          *
9547          * @return true if object can accept focus; otherwise false
9548          */
9549         public boolean isFocusTraversable() {
9550             return Component.this.isFocusTraversable();
9551         }
9552 
9553         /**
9554          * Requests focus for this object.
9555          */
9556         public void requestFocus() {
9557             Component.this.requestFocus();
9558         }
9559 
9560         /**
9561          * Adds the specified focus listener to receive focus events from this
9562          * component.
9563          *
9564          * @param l the focus listener
9565          */
9566         public void addFocusListener(FocusListener l) {
9567             Component.this.addFocusListener(l);
9568         }
9569 
9570         /**
9571          * Removes the specified focus listener so it no longer receives focus
9572          * events from this component.
9573          *
9574          * @param l the focus listener
9575          */
9576         public void removeFocusListener(FocusListener l) {
9577             Component.this.removeFocusListener(l);
9578         }
9579 
9580     } // inner class AccessibleAWTComponent
9581 
9582 
9583     /**
9584      * Gets the index of this object in its accessible parent.
9585      * If this object does not have an accessible parent, returns
9586      * -1.
9587      *
9588      * @return the index of this object in its accessible parent
9589      */
9590     int getAccessibleIndexInParent() {
9591         synchronized (getTreeLock()) {
9592             int index = -1;
9593             Container parent = this.getParent();
9594             if (parent != null && parent instanceof Accessible) {
9595                 Component ca[] = parent.getComponents();
9596                 for (int i = 0; i < ca.length; i++) {
9597                     if (ca[i] instanceof Accessible) {
9598                         index++;
9599                     }
9600                     if (this.equals(ca[i])) {
9601                         return index;
9602                     }
9603                 }
9604             }
9605             return -1;
9606         }
9607     }
9608 
9609     /**
9610      * Gets the current state set of this object.
9611      *
9612      * @return an instance of <code>AccessibleStateSet</code>
9613      *    containing the current state set of the object
9614      * @see AccessibleState
9615      */
9616     AccessibleStateSet getAccessibleStateSet() {
9617         synchronized (getTreeLock()) {
9618             AccessibleStateSet states = new AccessibleStateSet();
9619             if (this.isEnabled()) {
9620                 states.add(AccessibleState.ENABLED);
9621             }
9622             if (this.isFocusTraversable()) {
9623                 states.add(AccessibleState.FOCUSABLE);
9624             }
9625             if (this.isVisible()) {
9626                 states.add(AccessibleState.VISIBLE);
9627             }
9628             if (this.isShowing()) {
9629                 states.add(AccessibleState.SHOWING);
9630             }
9631             if (this.isFocusOwner()) {
9632                 states.add(AccessibleState.FOCUSED);
9633             }
9634             if (this instanceof Accessible) {
9635                 AccessibleContext ac = ((Accessible) this).getAccessibleContext();
9636                 if (ac != null) {
9637                     Accessible ap = ac.getAccessibleParent();
9638                     if (ap != null) {
9639                         AccessibleContext pac = ap.getAccessibleContext();
9640                         if (pac != null) {
9641                             AccessibleSelection as = pac.getAccessibleSelection();
9642                             if (as != null) {
9643                                 states.add(AccessibleState.SELECTABLE);
9644                                 int i = ac.getAccessibleIndexInParent();
9645                                 if (i >= 0) {
9646                                     if (as.isAccessibleChildSelected(i)) {
9647                                         states.add(AccessibleState.SELECTED);
9648                                     }
9649                                 }
9650                             }
9651                         }
9652                     }
9653                 }
9654             }
9655             if (Component.isInstanceOf(this, "javax.swing.JComponent")) {
9656                 if (((javax.swing.JComponent) this).isOpaque()) {
9657                     states.add(AccessibleState.OPAQUE);
9658                 }
9659             }
9660             return states;
9661         }
9662     }
9663 
9664     /**
9665      * Checks that the given object is instance of the given class.
9666      * @param obj Object to be checked
9667      * @param className The name of the class. Must be fully-qualified class name.
9668      * @return true, if this object is instanceof given class,
9669      *         false, otherwise, or if obj or className is null
9670      */
9671     static boolean isInstanceOf(Object obj, String className) {
9672         if (obj == null) return false;
9673         if (className == null) return false;
9674 
9675         Class<?> cls = obj.getClass();
9676         while (cls != null) {
9677             if (cls.getName().equals(className)) {
9678                 return true;
9679             }
9680             cls = cls.getSuperclass();
9681         }
9682         return false;
9683     }
9684 
9685 
9686     // ************************** MIXING CODE *******************************
9687 
9688     /**
9689      * Check whether we can trust the current bounds of the component.
9690      * The return value of false indicates that the container of the
9691      * component is invalid, and therefore needs to be layed out, which would
9692      * probably mean changing the bounds of its children.
9693      * Null-layout of the container or absence of the container mean
9694      * the bounds of the component are final and can be trusted.
9695      */
9696     final boolean areBoundsValid() {
9697         Container cont = getContainer();
9698         return cont == null || cont.isValid() || cont.getLayout() == null;
9699     }
9700 
9701     /**
9702      * Applies the shape to the component
9703      * @param shape Shape to be applied to the component
9704      */
9705     void applyCompoundShape(Region shape) {
9706         checkTreeLock();
9707 
9708         if (!areBoundsValid()) {
9709             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
9710                 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid());
9711             }
9712             return;
9713         }
9714 
9715         if (!isLightweight()) {
9716             ComponentPeer peer = getPeer();
9717             if (peer != null) {
9718                 // The Region class has some optimizations. That's why
9719                 // we should manually check whether it's empty and
9720                 // substitute the object ourselves. Otherwise we end up
9721                 // with some incorrect Region object with loX being
9722                 // greater than the hiX for instance.
9723                 if (shape.isEmpty()) {
9724                     shape = Region.EMPTY_REGION;
9725                 }
9726 
9727 
9728                 // Note: the shape is not really copied/cloned. We create
9729                 // the Region object ourselves, so there's no any possibility
9730                 // to modify the object outside of the mixing code.
9731                 // Nullifying compoundShape means that the component has normal shape
9732                 // (or has no shape at all).
9733                 if (shape.equals(getNormalShape())) {
9734                     if (this.compoundShape == null) {
9735                         return;
9736                     }
9737                     this.compoundShape = null;
9738                     peer.applyShape(null);
9739                 } else {
9740                     if (shape.equals(getAppliedShape())) {
9741                         return;
9742                     }
9743                     this.compoundShape = shape;
9744                     Point compAbsolute = getLocationOnWindow();
9745                     if (mixingLog.isLoggable(PlatformLogger.Level.FINER)) {
9746                         mixingLog.fine("this = " + this +
9747                                 "; compAbsolute=" + compAbsolute + "; shape=" + shape);
9748                     }
9749                     peer.applyShape(shape.getTranslatedRegion(-compAbsolute.x, -compAbsolute.y));
9750                 }
9751             }
9752         }
9753     }
9754 
9755     /**
9756      * Returns the shape previously set with applyCompoundShape().
9757      * If the component is LW or no shape was applied yet,
9758      * the method returns the normal shape.
9759      */
9760     private Region getAppliedShape() {
9761         checkTreeLock();
9762         //XXX: if we allow LW components to have a shape, this must be changed
9763         return (this.compoundShape == null || isLightweight()) ? getNormalShape() : this.compoundShape;
9764     }
9765 
9766     Point getLocationOnWindow() {
9767         checkTreeLock();
9768         Point curLocation = getLocation();
9769 
9770         for (Container parent = getContainer();
9771                 parent != null && !(parent instanceof Window);
9772                 parent = parent.getContainer())
9773         {
9774             curLocation.x += parent.getX();
9775             curLocation.y += parent.getY();
9776         }
9777 
9778         return curLocation;
9779     }
9780 
9781     /**
9782      * Returns the full shape of the component located in window coordinates
9783      */
9784     final Region getNormalShape() {
9785         checkTreeLock();
9786         //XXX: we may take into account a user-specified shape for this component
9787         Point compAbsolute = getLocationOnWindow();
9788         return
9789             Region.getInstanceXYWH(
9790                     compAbsolute.x,
9791                     compAbsolute.y,
9792                     getWidth(),
9793                     getHeight()
9794             );
9795     }
9796 
9797     /**
9798      * Returns the "opaque shape" of the component.
9799      *
9800      * The opaque shape of a lightweight components is the actual shape that
9801      * needs to be cut off of the heavyweight components in order to mix this
9802      * lightweight component correctly with them.
9803      *
9804      * The method is overriden in the java.awt.Container to handle non-opaque
9805      * containers containing opaque children.
9806      *
9807      * See 6637655 for details.
9808      */
9809     Region getOpaqueShape() {
9810         checkTreeLock();
9811         if (mixingCutoutRegion != null) {
9812             return mixingCutoutRegion;
9813         } else {
9814             return getNormalShape();
9815         }
9816     }
9817 
9818     final int getSiblingIndexAbove() {
9819         checkTreeLock();
9820         Container parent = getContainer();
9821         if (parent == null) {
9822             return -1;
9823         }
9824 
9825         int nextAbove = parent.getComponentZOrder(this) - 1;
9826 
9827         return nextAbove < 0 ? -1 : nextAbove;
9828     }
9829 
9830     final ComponentPeer getHWPeerAboveMe() {
9831         checkTreeLock();
9832 
9833         Container cont = getContainer();
9834         int indexAbove = getSiblingIndexAbove();
9835 
9836         while (cont != null) {
9837             for (int i = indexAbove; i > -1; i--) {
9838                 Component comp = cont.getComponent(i);
9839                 if (comp != null && comp.isDisplayable() && !comp.isLightweight()) {
9840                     return comp.getPeer();
9841                 }
9842             }
9843             // traversing the hierarchy up to the closest HW container;
9844             // further traversing may return a component that is not actually
9845             // a native sibling of this component and this kind of z-order
9846             // request may not be allowed by the underlying system (6852051).
9847             if (!cont.isLightweight()) {
9848                 break;
9849             }
9850 
9851             indexAbove = cont.getSiblingIndexAbove();
9852             cont = cont.getContainer();
9853         }
9854 
9855         return null;
9856     }
9857 
9858     final int getSiblingIndexBelow() {
9859         checkTreeLock();
9860         Container parent = getContainer();
9861         if (parent == null) {
9862             return -1;
9863         }
9864 
9865         int nextBelow = parent.getComponentZOrder(this) + 1;
9866 
9867         return nextBelow >= parent.getComponentCount() ? -1 : nextBelow;
9868     }
9869 
9870     final boolean isNonOpaqueForMixing() {
9871         return mixingCutoutRegion != null &&
9872             mixingCutoutRegion.isEmpty();
9873     }
9874 
9875     private Region calculateCurrentShape() {
9876         checkTreeLock();
9877         Region s = getNormalShape();
9878 
9879         if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
9880             mixingLog.fine("this = " + this + "; normalShape=" + s);
9881         }
9882 
9883         if (getContainer() != null) {
9884             Component comp = this;
9885             Container cont = comp.getContainer();
9886 
9887             while (cont != null) {
9888                 for (int index = comp.getSiblingIndexAbove(); index != -1; --index) {
9889                     /* It is assumed that:
9890                      *
9891                      *    getComponent(getContainer().getComponentZOrder(comp)) == comp
9892                      *
9893                      * The assumption has been made according to the current
9894                      * implementation of the Container class.
9895                      */
9896                     Component c = cont.getComponent(index);
9897                     if (c.isLightweight() && c.isShowing()) {
9898                         s = s.getDifference(c.getOpaqueShape());
9899                     }
9900                 }
9901 
9902                 if (cont.isLightweight()) {
9903                     s = s.getIntersection(cont.getNormalShape());
9904                 } else {
9905                     break;
9906                 }
9907 
9908                 comp = cont;
9909                 cont = cont.getContainer();
9910             }
9911         }
9912 
9913         if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
9914             mixingLog.fine("currentShape=" + s);
9915         }
9916 
9917         return s;
9918     }
9919 
9920     void applyCurrentShape() {
9921         checkTreeLock();
9922         if (!areBoundsValid()) {
9923             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
9924                 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid());
9925             }
9926             return; // Because applyCompoundShape() ignores such components anyway
9927         }
9928         if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
9929             mixingLog.fine("this = " + this);
9930         }
9931         applyCompoundShape(calculateCurrentShape());
9932     }
9933 
9934     final void subtractAndApplyShape(Region s) {
9935         checkTreeLock();
9936 
9937         if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
9938             mixingLog.fine("this = " + this + "; s=" + s);
9939         }
9940 
9941         applyCompoundShape(getAppliedShape().getDifference(s));
9942     }
9943 
9944     private final void applyCurrentShapeBelowMe() {
9945         checkTreeLock();
9946         Container parent = getContainer();
9947         if (parent != null && parent.isShowing()) {
9948             // First, reapply shapes of my siblings
9949             parent.recursiveApplyCurrentShape(getSiblingIndexBelow());
9950 
9951             // Second, if my container is non-opaque, reapply shapes of siblings of my container
9952             Container parent2 = parent.getContainer();
9953             while (!parent.isOpaque() && parent2 != null) {
9954                 parent2.recursiveApplyCurrentShape(parent.getSiblingIndexBelow());
9955 
9956                 parent = parent2;
9957                 parent2 = parent.getContainer();
9958             }
9959         }
9960     }
9961 
9962     final void subtractAndApplyShapeBelowMe() {
9963         checkTreeLock();
9964         Container parent = getContainer();
9965         if (parent != null && isShowing()) {
9966             Region opaqueShape = getOpaqueShape();
9967 
9968             // First, cut my siblings
9969             parent.recursiveSubtractAndApplyShape(opaqueShape, getSiblingIndexBelow());
9970 
9971             // Second, if my container is non-opaque, cut siblings of my container
9972             Container parent2 = parent.getContainer();
9973             while (!parent.isOpaque() && parent2 != null) {
9974                 parent2.recursiveSubtractAndApplyShape(opaqueShape, parent.getSiblingIndexBelow());
9975 
9976                 parent = parent2;
9977                 parent2 = parent.getContainer();
9978             }
9979         }
9980     }
9981 
9982     void mixOnShowing() {
9983         synchronized (getTreeLock()) {
9984             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
9985                 mixingLog.fine("this = " + this);
9986             }
9987             if (!isMixingNeeded()) {
9988                 return;
9989             }
9990             if (isLightweight()) {
9991                 subtractAndApplyShapeBelowMe();
9992             } else {
9993                 applyCurrentShape();
9994             }
9995         }
9996     }
9997 
9998     void mixOnHiding(boolean isLightweight) {
9999         // We cannot be sure that the peer exists at this point, so we need the argument
10000         //    to find out whether the hiding component is (well, actually was) a LW or a HW.
10001         synchronized (getTreeLock()) {
10002             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10003                 mixingLog.fine("this = " + this + "; isLightweight = " + isLightweight);
10004             }
10005             if (!isMixingNeeded()) {
10006                 return;
10007             }
10008             if (isLightweight) {
10009                 applyCurrentShapeBelowMe();
10010             }
10011         }
10012     }
10013 
10014     void mixOnReshaping() {
10015         synchronized (getTreeLock()) {
10016             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10017                 mixingLog.fine("this = " + this);
10018             }
10019             if (!isMixingNeeded()) {
10020                 return;
10021             }
10022             if (isLightweight()) {
10023                 applyCurrentShapeBelowMe();
10024             } else {
10025                 applyCurrentShape();
10026             }
10027         }
10028     }
10029 
10030     void mixOnZOrderChanging(int oldZorder, int newZorder) {
10031         synchronized (getTreeLock()) {
10032             boolean becameHigher = newZorder < oldZorder;
10033             Container parent = getContainer();
10034 
10035             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10036                 mixingLog.fine("this = " + this +
10037                     "; oldZorder=" + oldZorder + "; newZorder=" + newZorder + "; parent=" + parent);
10038             }
10039             if (!isMixingNeeded()) {
10040                 return;
10041             }
10042             if (isLightweight()) {
10043                 if (becameHigher) {
10044                     if (parent != null && isShowing()) {
10045                         parent.recursiveSubtractAndApplyShape(getOpaqueShape(), getSiblingIndexBelow(), oldZorder);
10046                     }
10047                 } else {
10048                     if (parent != null) {
10049                         parent.recursiveApplyCurrentShape(oldZorder, newZorder);
10050                     }
10051                 }
10052             } else {
10053                 if (becameHigher) {
10054                     applyCurrentShape();
10055                 } else {
10056                     if (parent != null) {
10057                         Region shape = getAppliedShape();
10058 
10059                         for (int index = oldZorder; index < newZorder; index++) {
10060                             Component c = parent.getComponent(index);
10061                             if (c.isLightweight() && c.isShowing()) {
10062                                 shape = shape.getDifference(c.getOpaqueShape());
10063                             }
10064                         }
10065                         applyCompoundShape(shape);
10066                     }
10067                 }
10068             }
10069         }
10070     }
10071 
10072     void mixOnValidating() {
10073         // This method gets overriden in the Container. Obviously, a plain
10074         // non-container components don't need to handle validation.
10075     }
10076 
10077     final boolean isMixingNeeded() {
10078         if (SunToolkit.getSunAwtDisableMixing()) {
10079             if (mixingLog.isLoggable(PlatformLogger.Level.FINEST)) {
10080                 mixingLog.finest("this = " + this + "; Mixing disabled via sun.awt.disableMixing");
10081             }
10082             return false;
10083         }
10084         if (!areBoundsValid()) {
10085             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10086                 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid());
10087             }
10088             return false;
10089         }
10090         Window window = getContainingWindow();
10091         if (window != null) {
10092             if (!window.hasHeavyweightDescendants() || !window.hasLightweightDescendants() || window.isDisposing()) {
10093                 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10094                     mixingLog.fine("containing window = " + window +
10095                             "; has h/w descendants = " + window.hasHeavyweightDescendants() +
10096                             "; has l/w descendants = " + window.hasLightweightDescendants() +
10097                             "; disposing = " + window.isDisposing());
10098                 }
10099                 return false;
10100             }
10101         } else {
10102             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
10103                 mixingLog.fine("this = " + this + "; containing window is null");
10104             }
10105             return false;
10106         }
10107         return true;
10108     }
10109 
10110     // ****************** END OF MIXING CODE ********************************
10111 
10112     // Note that the method is overriden in the Window class,
10113     // a window doesn't need to be updated in the Z-order.
10114     void updateZOrder() {
10115         peer.setZOrder(getHWPeerAboveMe());
10116     }
10117 
10118 }