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