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