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