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