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