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