1 /*
   2  * Copyright (c) 1995, 2017, 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.awt.dnd.DropTarget;
  28 
  29 import java.awt.event.*;
  30 
  31 import java.awt.peer.ContainerPeer;
  32 import java.awt.peer.ComponentPeer;
  33 import java.awt.peer.LightweightPeer;
  34 
  35 import java.beans.PropertyChangeListener;
  36 
  37 import java.io.IOException;
  38 import java.io.ObjectInputStream;
  39 import java.io.ObjectOutputStream;
  40 import java.io.ObjectStreamField;
  41 import java.io.PrintStream;
  42 import java.io.PrintWriter;
  43 
  44 import java.lang.ref.WeakReference;
  45 import java.security.AccessController;
  46 
  47 import java.util.ArrayList;
  48 import java.util.EventListener;
  49 import java.util.HashSet;
  50 import java.util.Set;
  51 
  52 import javax.accessibility.*;
  53 
  54 import sun.util.logging.PlatformLogger;
  55 
  56 import sun.awt.AppContext;
  57 import sun.awt.AWTAccessor;
  58 import sun.awt.AWTAccessor.MouseEventAccessor;
  59 import sun.awt.PeerEvent;
  60 import sun.awt.SunToolkit;
  61 
  62 import sun.awt.dnd.SunDropTargetEvent;
  63 
  64 import sun.java2d.pipe.Region;
  65 
  66 import sun.security.action.GetBooleanAction;
  67 
  68 /**
  69  * A generic Abstract Window Toolkit(AWT) container object is a component
  70  * that can contain other AWT components.
  71  * <p>
  72  * Components added to a container are tracked in a list.  The order
  73  * of the list will define the components' front-to-back stacking order
  74  * within the container.  If no index is specified when adding a
  75  * component to a container, it will be added to the end of the list
  76  * (and hence to the bottom of the stacking order).
  77  * <p>
  78  * <b>Note</b>: For details on the focus subsystem, see
  79  * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
  80  * How to Use the Focus Subsystem</a>,
  81  * a section in <em>The Java Tutorial</em>, and the
  82  * <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
  83  * for more information.
  84  *
  85  * @author      Arthur van Hoff
  86  * @author      Sami Shaio
  87  * @see       #add(java.awt.Component, int)
  88  * @see       #getComponent(int)
  89  * @see       LayoutManager
  90  * @since     1.0
  91  */
  92 public class Container extends Component {
  93 
  94     private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.Container");
  95     private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.Container");
  96 
  97     private static final Component[] EMPTY_ARRAY = new Component[0];
  98 
  99     /**
 100      * The components in this container.
 101      * @see #add
 102      * @see #getComponents
 103      */
 104     private java.util.List<Component> component = new ArrayList<>();
 105 
 106     /**
 107      * Layout manager for this container.
 108      * @see #doLayout
 109      * @see #setLayout
 110      * @see #getLayout
 111      */
 112     LayoutManager layoutMgr;
 113 
 114     /**
 115      * Event router for lightweight components.  If this container
 116      * is native, this dispatcher takes care of forwarding and
 117      * retargeting the events to lightweight components contained
 118      * (if any).
 119      */
 120     private LightweightDispatcher dispatcher;
 121 
 122     /**
 123      * The focus traversal policy that will manage keyboard traversal of this
 124      * Container's children, if this Container is a focus cycle root. If the
 125      * value is null, this Container inherits its policy from its focus-cycle-
 126      * root ancestor. If all such ancestors of this Container have null
 127      * policies, then the current KeyboardFocusManager's default policy is
 128      * used. If the value is non-null, this policy will be inherited by all
 129      * focus-cycle-root children that have no keyboard-traversal policy of
 130      * their own (as will, recursively, their focus-cycle-root children).
 131      * <p>
 132      * If this Container is not a focus cycle root, the value will be
 133      * remembered, but will not be used or inherited by this or any other
 134      * Containers until this Container is made a focus cycle root.
 135      *
 136      * @see #setFocusTraversalPolicy
 137      * @see #getFocusTraversalPolicy
 138      * @since 1.4
 139      */
 140     private transient FocusTraversalPolicy focusTraversalPolicy;
 141 
 142     /**
 143      * Indicates whether this Component is the root of a focus traversal cycle.
 144      * Once focus enters a traversal cycle, typically it cannot leave it via
 145      * focus traversal unless one of the up- or down-cycle keys is pressed.
 146      * Normal traversal is limited to this Container, and all of this
 147      * Container's descendants that are not descendants of inferior focus cycle
 148      * roots.
 149      *
 150      * @see #setFocusCycleRoot
 151      * @see #isFocusCycleRoot
 152      * @since 1.4
 153      */
 154     private boolean focusCycleRoot = false;
 155 
 156 
 157     /**
 158      * Stores the value of focusTraversalPolicyProvider property.
 159      * @since 1.5
 160      * @see #setFocusTraversalPolicyProvider
 161      */
 162     private boolean focusTraversalPolicyProvider;
 163 
 164     // keeps track of the threads that are printing this component
 165     private transient Set<Thread> printingThreads;
 166     // True if there is at least one thread that's printing this component
 167     private transient boolean printing = false;
 168 
 169     transient ContainerListener containerListener;
 170 
 171     /* HierarchyListener and HierarchyBoundsListener support */
 172     transient int listeningChildren;
 173     transient int listeningBoundsChildren;
 174     transient int descendantsCount;
 175 
 176     /* Non-opaque window support -- see Window.setLayersOpaque */
 177     transient Color preserveBackgroundColor = null;
 178 
 179     /**
 180      * JDK 1.1 serialVersionUID
 181      */
 182     private static final long serialVersionUID = 4613797578919906343L;
 183 
 184     /**
 185      * A constant which toggles one of the controllable behaviors
 186      * of {@code getMouseEventTarget}. It is used to specify whether
 187      * the method can return the Container on which it is originally called
 188      * in case if none of its children are the current mouse event targets.
 189      *
 190      * @see #getMouseEventTarget(int, int, boolean)
 191      */
 192     static final boolean INCLUDE_SELF = true;
 193 
 194     /**
 195      * A constant which toggles one of the controllable behaviors
 196      * of {@code getMouseEventTarget}. It is used to specify whether
 197      * the method should search only lightweight components.
 198      *
 199      * @see #getMouseEventTarget(int, int, boolean)
 200      */
 201     static final boolean SEARCH_HEAVYWEIGHTS = true;
 202 
 203     /*
 204      * Number of HW or LW components in this container (including
 205      * all descendant containers).
 206      */
 207     private transient int numOfHWComponents = 0;
 208     private transient int numOfLWComponents = 0;
 209 
 210     private static final PlatformLogger mixingLog = PlatformLogger.getLogger("java.awt.mixing.Container");
 211 
 212     /**
 213      * @serialField ncomponents                     int
 214      *       The number of components in this container.
 215      *       This value can be null.
 216      * @serialField component                       Component[]
 217      *       The components in this container.
 218      * @serialField layoutMgr                       LayoutManager
 219      *       Layout manager for this container.
 220      * @serialField dispatcher                      LightweightDispatcher
 221      *       Event router for lightweight components.  If this container
 222      *       is native, this dispatcher takes care of forwarding and
 223      *       retargeting the events to lightweight components contained
 224      *       (if any).
 225      * @serialField maxSize                         Dimension
 226      *       Maximum size of this Container.
 227      * @serialField focusCycleRoot                  boolean
 228      *       Indicates whether this Component is the root of a focus traversal cycle.
 229      *       Once focus enters a traversal cycle, typically it cannot leave it via
 230      *       focus traversal unless one of the up- or down-cycle keys is pressed.
 231      *       Normal traversal is limited to this Container, and all of this
 232      *       Container's descendants that are not descendants of inferior focus cycle
 233      *       roots.
 234      * @serialField containerSerializedDataVersion  int
 235      *       Container Serial Data Version.
 236      * @serialField focusTraversalPolicyProvider    boolean
 237      *       Stores the value of focusTraversalPolicyProvider property.
 238      */
 239     private static final ObjectStreamField[] serialPersistentFields = {
 240         new ObjectStreamField("ncomponents", Integer.TYPE),
 241         new ObjectStreamField("component", Component[].class),
 242         new ObjectStreamField("layoutMgr", LayoutManager.class),
 243         new ObjectStreamField("dispatcher", LightweightDispatcher.class),
 244         new ObjectStreamField("maxSize", Dimension.class),
 245         new ObjectStreamField("focusCycleRoot", Boolean.TYPE),
 246         new ObjectStreamField("containerSerializedDataVersion", Integer.TYPE),
 247         new ObjectStreamField("focusTraversalPolicyProvider", Boolean.TYPE),
 248     };
 249 
 250     static {
 251         /* ensure that the necessary native libraries are loaded */
 252         Toolkit.loadLibraries();
 253         if (!GraphicsEnvironment.isHeadless()) {
 254             initIDs();
 255         }
 256 
 257         AWTAccessor.setContainerAccessor(new AWTAccessor.ContainerAccessor() {
 258             @Override
 259             public void validateUnconditionally(Container cont) {
 260                 cont.validateUnconditionally();
 261             }
 262 
 263             @Override
 264             public Component findComponentAt(Container cont, int x, int y,
 265                     boolean ignoreEnabled) {
 266                 return cont.findComponentAt(x, y, ignoreEnabled);
 267             }
 268 
 269             @Override
 270             public void startLWModal(Container cont) {
 271                 cont.startLWModal();
 272             }
 273 
 274             @Override
 275             public void stopLWModal(Container cont) {
 276                 cont.stopLWModal();
 277             }
 278         });
 279     }
 280 
 281     /**
 282      * Initialize JNI field and method IDs for fields that may be
 283        called from C.
 284      */
 285     private static native void initIDs();
 286 
 287     /**
 288      * Constructs a new Container. Containers can be extended directly,
 289      * but are lightweight in this case and must be contained by a parent
 290      * somewhere higher up in the component tree that is native.
 291      * (such as Frame for example).
 292      */
 293     public Container() {
 294     }
 295     @SuppressWarnings({"unchecked","rawtypes"})
 296     void initializeFocusTraversalKeys() {
 297         focusTraversalKeys = new Set[4];
 298     }
 299 
 300     /**
 301      * Gets the number of components in this panel.
 302      * <p>
 303      * Note: This method should be called under AWT tree lock.
 304      *
 305      * @return    the number of components in this panel.
 306      * @see       #getComponent
 307      * @since     1.1
 308      * @see Component#getTreeLock()
 309      */
 310     public int getComponentCount() {
 311         return countComponents();
 312     }
 313 
 314     /**
 315      * Returns the number of components in this container.
 316      *
 317      * @return the number of components in this container
 318      * @deprecated As of JDK version 1.1,
 319      * replaced by getComponentCount().
 320      */
 321     @Deprecated
 322     public int countComponents() {
 323         // This method is not synchronized under AWT tree lock.
 324         // Instead, the calling code is responsible for the
 325         // synchronization. See 6784816 for details.
 326         return component.size();
 327     }
 328 
 329     /**
 330      * Gets the nth component in this container.
 331      * <p>
 332      * Note: This method should be called under AWT tree lock.
 333      *
 334      * @param      n   the index of the component to get.
 335      * @return     the n<sup>th</sup> component in this container.
 336      * @exception  ArrayIndexOutOfBoundsException
 337      *                 if the n<sup>th</sup> value does not exist.
 338      * @see Component#getTreeLock()
 339      */
 340     public Component getComponent(int n) {
 341         // This method is not synchronized under AWT tree lock.
 342         // Instead, the calling code is responsible for the
 343         // synchronization. See 6784816 for details.
 344         try {
 345             return component.get(n);
 346         } catch (IndexOutOfBoundsException z) {
 347             throw new ArrayIndexOutOfBoundsException("No such child: " + n);
 348         }
 349     }
 350 
 351     /**
 352      * Gets all the components in this container.
 353      * <p>
 354      * Note: This method should be called under AWT tree lock.
 355      *
 356      * @return    an array of all the components in this container.
 357      * @see Component#getTreeLock()
 358      */
 359     public Component[] getComponents() {
 360         // This method is not synchronized under AWT tree lock.
 361         // Instead, the calling code is responsible for the
 362         // synchronization. See 6784816 for details.
 363         return getComponents_NoClientCode();
 364     }
 365 
 366     // NOTE: This method may be called by privileged threads.
 367     //       This functionality is implemented in a package-private method
 368     //       to insure that it cannot be overridden by client subclasses.
 369     //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
 370     final Component[] getComponents_NoClientCode() {
 371         return component.toArray(EMPTY_ARRAY);
 372     }
 373 
 374     /*
 375      * Wrapper for getComponents() method with a proper synchronization.
 376      */
 377     Component[] getComponentsSync() {
 378         synchronized (getTreeLock()) {
 379             return getComponents();
 380         }
 381     }
 382 
 383     /**
 384      * Determines the insets of this container, which indicate the size
 385      * of the container's border.
 386      * <p>
 387      * A {@code Frame} object, for example, has a top inset that
 388      * corresponds to the height of the frame's title bar.
 389      * @return    the insets of this container.
 390      * @see       Insets
 391      * @see       LayoutManager
 392      * @since     1.1
 393      */
 394     public Insets getInsets() {
 395         return insets();
 396     }
 397 
 398     /**
 399      * Returns the insets for this container.
 400      *
 401      * @deprecated As of JDK version 1.1,
 402      * replaced by {@code getInsets()}.
 403      * @return the insets for this container
 404      */
 405     @Deprecated
 406     public Insets insets() {
 407         ComponentPeer peer = this.peer;
 408         if (peer instanceof ContainerPeer) {
 409             ContainerPeer cpeer = (ContainerPeer)peer;
 410             return (Insets)cpeer.getInsets().clone();
 411         }
 412         return new Insets(0, 0, 0, 0);
 413     }
 414 
 415     /**
 416      * Appends the specified component to the end of this container.
 417      * This is a convenience method for {@link #addImpl}.
 418      * <p>
 419      * This method changes layout-related information, and therefore,
 420      * invalidates the component hierarchy. If the container has already been
 421      * displayed, the hierarchy must be validated thereafter in order to
 422      * display the added component.
 423      *
 424      * @param     comp   the component to be added
 425      * @exception NullPointerException if {@code comp} is {@code null}
 426      * @see #addImpl
 427      * @see #invalidate
 428      * @see #validate
 429      * @see javax.swing.JComponent#revalidate()
 430      * @return    the component argument
 431      */
 432     public Component add(Component comp) {
 433         addImpl(comp, null, -1);
 434         return comp;
 435     }
 436 
 437     /**
 438      * Adds the specified component to this container.
 439      * This is a convenience method for {@link #addImpl}.
 440      * <p>
 441      * This method is obsolete as of 1.1.  Please use the
 442      * method {@code add(Component, Object)} instead.
 443      * <p>
 444      * This method changes layout-related information, and therefore,
 445      * invalidates the component hierarchy. If the container has already been
 446      * displayed, the hierarchy must be validated thereafter in order to
 447      * display the added component.
 448      *
 449      * @param  name the name of the component to be added
 450      * @param  comp the component to be added
 451      * @return the component added
 452      * @exception NullPointerException if {@code comp} is {@code null}
 453      * @see #add(Component, Object)
 454      * @see #invalidate
 455      */
 456     public Component add(String name, Component comp) {
 457         addImpl(comp, name, -1);
 458         return comp;
 459     }
 460 
 461     /**
 462      * Adds the specified component to this container at the given
 463      * position.
 464      * This is a convenience method for {@link #addImpl}.
 465      * <p>
 466      * This method changes layout-related information, and therefore,
 467      * invalidates the component hierarchy. If the container has already been
 468      * displayed, the hierarchy must be validated thereafter in order to
 469      * display the added component.
 470      *
 471      *
 472      * @param     comp   the component to be added
 473      * @param     index    the position at which to insert the component,
 474      *                   or {@code -1} to append the component to the end
 475      * @exception NullPointerException if {@code comp} is {@code null}
 476      * @exception IllegalArgumentException if {@code index} is invalid (see
 477      *            {@link #addImpl} for details)
 478      * @return    the component {@code comp}
 479      * @see #addImpl
 480      * @see #remove
 481      * @see #invalidate
 482      * @see #validate
 483      * @see javax.swing.JComponent#revalidate()
 484      */
 485     public Component add(Component comp, int index) {
 486         addImpl(comp, null, index);
 487         return comp;
 488     }
 489 
 490     /**
 491      * Checks that the component
 492      * isn't supposed to be added into itself.
 493      */
 494     private void checkAddToSelf(Component comp){
 495         if (comp instanceof Container) {
 496             for (Container cn = this; cn != null; cn=cn.parent) {
 497                 if (cn == comp) {
 498                     throw new IllegalArgumentException("adding container's parent to itself");
 499                 }
 500             }
 501         }
 502     }
 503 
 504     /**
 505      * Checks that the component is not a Window instance.
 506      */
 507     private void checkNotAWindow(Component comp){
 508         if (comp instanceof Window) {
 509             throw new IllegalArgumentException("adding a window to a container");
 510         }
 511     }
 512 
 513     /**
 514      * Checks that the component comp can be added to this container
 515      * Checks :  index in bounds of container's size,
 516      * comp is not one of this container's parents,
 517      * and comp is not a window.
 518      * Comp and container must be on the same GraphicsDevice.
 519      * if comp is container, all sub-components must be on
 520      * same GraphicsDevice.
 521      *
 522      * @since 1.5
 523      */
 524     private void checkAdding(Component comp, int index) {
 525         checkTreeLock();
 526 
 527         GraphicsConfiguration thisGC = getGraphicsConfiguration();
 528 
 529         if (index > component.size() || index < 0) {
 530             throw new IllegalArgumentException("illegal component position");
 531         }
 532         if (comp.parent == this) {
 533             if (index == component.size()) {
 534                 throw new IllegalArgumentException("illegal component position " +
 535                                                    index + " should be less than " + component.size());
 536             }
 537         }
 538         checkAddToSelf(comp);
 539         checkNotAWindow(comp);
 540 
 541         Window thisTopLevel = getContainingWindow();
 542         Window compTopLevel = comp.getContainingWindow();
 543         if (thisTopLevel != compTopLevel) {
 544             throw new IllegalArgumentException("component and container should be in the same top-level window");
 545         }
 546         if (thisGC != null) {
 547             comp.checkGD(thisGC.getDevice().getIDstring());
 548         }
 549     }
 550 
 551     /**
 552      * Removes component comp from this container without making unnecessary changes
 553      * and generating unnecessary events. This function intended to perform optimized
 554      * remove, for example, if newParent and current parent are the same it just changes
 555      * index without calling removeNotify.
 556      * Note: Should be called while holding treeLock
 557      * Returns whether removeNotify was invoked
 558      * @since: 1.5
 559      */
 560     private boolean removeDelicately(Component comp, Container newParent, int newIndex) {
 561         checkTreeLock();
 562 
 563         int index = getComponentZOrder(comp);
 564         boolean needRemoveNotify = isRemoveNotifyNeeded(comp, this, newParent);
 565         if (needRemoveNotify) {
 566             comp.removeNotify();
 567         }
 568         if (newParent != this) {
 569             if (layoutMgr != null) {
 570                 layoutMgr.removeLayoutComponent(comp);
 571             }
 572             adjustListeningChildren(AWTEvent.HIERARCHY_EVENT_MASK,
 573                                     -comp.numListening(AWTEvent.HIERARCHY_EVENT_MASK));
 574             adjustListeningChildren(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK,
 575                                     -comp.numListening(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
 576             adjustDescendants(-(comp.countHierarchyMembers()));
 577 
 578             comp.parent = null;
 579             if (needRemoveNotify) {
 580                 comp.setGraphicsConfiguration(null);
 581             }
 582             component.remove(index);
 583 
 584             invalidateIfValid();
 585         } else {
 586             // We should remove component and then
 587             // add it by the newIndex without newIndex decrement if even we shift components to the left
 588             // after remove. Consult the rules below:
 589             // 2->4: 012345 -> 013425, 2->5: 012345 -> 013452
 590             // 4->2: 012345 -> 014235
 591             component.remove(index);
 592             component.add(newIndex, comp);
 593         }
 594         if (comp.parent == null) { // was actually removed
 595             if (containerListener != null ||
 596                 (eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 ||
 597                 Toolkit.enabledOnToolkit(AWTEvent.CONTAINER_EVENT_MASK)) {
 598                 ContainerEvent e = new ContainerEvent(this,
 599                                                       ContainerEvent.COMPONENT_REMOVED,
 600                                                       comp);
 601                 dispatchEvent(e);
 602 
 603             }
 604             comp.createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, comp,
 605                                        this, HierarchyEvent.PARENT_CHANGED,
 606                                        Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
 607             if (peer != null && layoutMgr == null && isVisible()) {
 608                 updateCursorImmediately();
 609             }
 610         }
 611         return needRemoveNotify;
 612     }
 613 
 614     /**
 615      * Checks whether this container can contain component which is focus owner.
 616      * Verifies that container is enable and showing, and if it is focus cycle root
 617      * its FTP allows component to be focus owner
 618      * @since 1.5
 619      */
 620     boolean canContainFocusOwner(Component focusOwnerCandidate) {
 621         if (!(isEnabled() && isDisplayable()
 622               && isVisible() && isFocusable()))
 623         {
 624             return false;
 625         }
 626         if (isFocusCycleRoot()) {
 627             FocusTraversalPolicy policy = getFocusTraversalPolicy();
 628             if (policy instanceof DefaultFocusTraversalPolicy) {
 629                 if (!((DefaultFocusTraversalPolicy)policy).accept(focusOwnerCandidate)) {
 630                     return false;
 631                 }
 632             }
 633         }
 634         synchronized(getTreeLock()) {
 635             if (parent != null) {
 636                 return parent.canContainFocusOwner(focusOwnerCandidate);
 637             }
 638         }
 639         return true;
 640     }
 641 
 642     /**
 643      * Checks whether or not this container has heavyweight children.
 644      * Note: Should be called while holding tree lock
 645      * @return true if there is at least one heavyweight children in a container, false otherwise
 646      * @since 1.5
 647      */
 648     final boolean hasHeavyweightDescendants() {
 649         checkTreeLock();
 650         return numOfHWComponents > 0;
 651     }
 652 
 653     /**
 654      * Checks whether or not this container has lightweight children.
 655      * Note: Should be called while holding tree lock
 656      * @return true if there is at least one lightweight children in a container, false otherwise
 657      * @since 1.7
 658      */
 659     final boolean hasLightweightDescendants() {
 660         checkTreeLock();
 661         return numOfLWComponents > 0;
 662     }
 663 
 664     /**
 665      * Returns closest heavyweight component to this container. If this container is heavyweight
 666      * returns this.
 667      * @since 1.5
 668      */
 669     Container getHeavyweightContainer() {
 670         checkTreeLock();
 671         if (peer != null && !(peer instanceof LightweightPeer)) {
 672             return this;
 673         } else {
 674             return getNativeContainer();
 675         }
 676     }
 677 
 678     /**
 679      * Detects whether or not remove from current parent and adding to new parent requires call of
 680      * removeNotify on the component. Since removeNotify destroys native window this might (not)
 681      * be required. For example, if new container and old containers are the same we don't need to
 682      * destroy native window.
 683      * @since: 1.5
 684      */
 685     private static boolean isRemoveNotifyNeeded(Component comp, Container oldContainer, Container newContainer) {
 686         if (oldContainer == null) { // Component didn't have parent - no removeNotify
 687             return false;
 688         }
 689         if (comp.peer == null) { // Component didn't have peer - no removeNotify
 690             return false;
 691         }
 692         if (newContainer.peer == null) {
 693             // Component has peer but new Container doesn't - call removeNotify
 694             return true;
 695         }
 696 
 697         // If component is lightweight non-Container or lightweight Container with all but heavyweight
 698         // children there is no need to call remove notify
 699         if (comp.isLightweight()) {
 700             boolean isContainer = comp instanceof Container;
 701 
 702             if (!isContainer || (isContainer && !((Container)comp).hasHeavyweightDescendants())) {
 703                 return false;
 704             }
 705         }
 706 
 707         // If this point is reached, then the comp is either a HW or a LW container with HW descendants.
 708 
 709         // All three components have peers, check for peer change
 710         Container newNativeContainer = oldContainer.getHeavyweightContainer();
 711         Container oldNativeContainer = newContainer.getHeavyweightContainer();
 712         if (newNativeContainer != oldNativeContainer) {
 713             // Native containers change - check whether or not current platform supports
 714             // changing of widget hierarchy on native level without recreation.
 715             // The current implementation forbids reparenting of LW containers with HW descendants
 716             // into another native container w/o destroying the peers. Actually such an operation
 717             // is quite rare. If we ever need to save the peers, we'll have to slightly change the
 718             // addDelicately() method in order to handle such LW containers recursively, reparenting
 719             // each HW descendant independently.
 720             return !comp.peer.isReparentSupported();
 721         } else {
 722             return false;
 723         }
 724     }
 725 
 726     /**
 727      * Moves the specified component to the specified z-order index in
 728      * the container. The z-order determines the order that components
 729      * are painted; the component with the highest z-order paints first
 730      * and the component with the lowest z-order paints last.
 731      * Where components overlap, the component with the lower
 732      * z-order paints over the component with the higher z-order.
 733      * <p>
 734      * If the component is a child of some other container, it is
 735      * removed from that container before being added to this container.
 736      * The important difference between this method and
 737      * {@code java.awt.Container.add(Component, int)} is that this method
 738      * doesn't call {@code removeNotify} on the component while
 739      * removing it from its previous container unless necessary and when
 740      * allowed by the underlying native windowing system. This way, if the
 741      * component has the keyboard focus, it maintains the focus when
 742      * moved to the new position.
 743      * <p>
 744      * This property is guaranteed to apply only to lightweight
 745      * non-{@code Container} components.
 746      * <p>
 747      * This method changes layout-related information, and therefore,
 748      * invalidates the component hierarchy.
 749      * <p>
 750      * <b>Note</b>: Not all platforms support changing the z-order of
 751      * heavyweight components from one container into another without
 752      * the call to {@code removeNotify}. There is no way to detect
 753      * whether a platform supports this, so developers shouldn't make
 754      * any assumptions.
 755      *
 756      * @param     comp the component to be moved
 757      * @param     index the position in the container's list to
 758      *            insert the component, where {@code getComponentCount()}
 759      *            appends to the end
 760      * @exception NullPointerException if {@code comp} is
 761      *            {@code null}
 762      * @exception IllegalArgumentException if {@code comp} is one of the
 763      *            container's parents
 764      * @exception IllegalArgumentException if {@code index} is not in
 765      *            the range {@code [0, getComponentCount()]} for moving
 766      *            between containers, or not in the range
 767      *            {@code [0, getComponentCount()-1]} for moving inside
 768      *            a container
 769      * @exception IllegalArgumentException if adding a container to itself
 770      * @exception IllegalArgumentException if adding a {@code Window}
 771      *            to a container
 772      * @see #getComponentZOrder(java.awt.Component)
 773      * @see #invalidate
 774      * @since 1.5
 775      */
 776     public void setComponentZOrder(Component comp, int index) {
 777          synchronized (getTreeLock()) {
 778              // Store parent because remove will clear it
 779              Container curParent = comp.parent;
 780              int oldZindex = getComponentZOrder(comp);
 781 
 782              if (curParent == this && index == oldZindex) {
 783                  return;
 784              }
 785              checkAdding(comp, index);
 786 
 787              boolean peerRecreated = (curParent != null) ?
 788                  curParent.removeDelicately(comp, this, index) : false;
 789 
 790              addDelicately(comp, curParent, index);
 791 
 792              // If the oldZindex == -1, the component gets inserted,
 793              // rather than it changes its z-order.
 794              if (!peerRecreated && oldZindex != -1) {
 795                  // The new 'index' cannot be == -1.
 796                  // It gets checked at the checkAdding() method.
 797                  // Therefore both oldZIndex and index denote
 798                  // some existing positions at this point and
 799                  // this is actually a Z-order changing.
 800                  comp.mixOnZOrderChanging(oldZindex, index);
 801              }
 802          }
 803     }
 804 
 805     /**
 806      * Traverses the tree of components and reparents children heavyweight component
 807      * to new heavyweight parent.
 808      * @since 1.5
 809      */
 810     @SuppressWarnings("deprecation")
 811     private void reparentTraverse(ContainerPeer parentPeer, Container child) {
 812         checkTreeLock();
 813 
 814         for (int i = 0; i < child.getComponentCount(); i++) {
 815             Component comp = child.getComponent(i);
 816             if (comp.isLightweight()) {
 817                 // If components is lightweight check if it is container
 818                 // If it is container it might contain heavyweight children we need to reparent
 819                 if (comp instanceof Container) {
 820                     reparentTraverse(parentPeer, (Container)comp);
 821                 }
 822             } else {
 823                 // Q: Need to update NativeInLightFixer?
 824                 comp.peer.reparent(parentPeer);
 825             }
 826         }
 827     }
 828 
 829     /**
 830      * Reparents child component peer to this container peer.
 831      * Container must be heavyweight.
 832      * @since 1.5
 833      */
 834     @SuppressWarnings("deprecation")
 835     private void reparentChild(Component comp) {
 836         checkTreeLock();
 837         if (comp == null) {
 838             return;
 839         }
 840         if (comp.isLightweight()) {
 841             // If component is lightweight container we need to reparent all its explicit  heavyweight children
 842             if (comp instanceof Container) {
 843                 // Traverse component's tree till depth-first until encountering heavyweight component
 844                 reparentTraverse((ContainerPeer)peer, (Container)comp);
 845             }
 846         } else {
 847             comp.peer.reparent((ContainerPeer) peer);
 848         }
 849     }
 850 
 851     /**
 852      * Adds component to this container. Tries to minimize side effects of this adding -
 853      * doesn't call remove notify if it is not required.
 854      * @since 1.5
 855      */
 856     private void addDelicately(Component comp, Container curParent, int index) {
 857         checkTreeLock();
 858 
 859         // Check if moving between containers
 860         if (curParent != this) {
 861             //index == -1 means add to the end.
 862             if (index == -1) {
 863                 component.add(comp);
 864             } else {
 865                 component.add(index, comp);
 866             }
 867             comp.parent = this;
 868             comp.setGraphicsConfiguration(getGraphicsConfiguration());
 869 
 870             adjustListeningChildren(AWTEvent.HIERARCHY_EVENT_MASK,
 871                                     comp.numListening(AWTEvent.HIERARCHY_EVENT_MASK));
 872             adjustListeningChildren(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK,
 873                                     comp.numListening(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
 874             adjustDescendants(comp.countHierarchyMembers());
 875         } else {
 876             if (index < component.size()) {
 877                 component.set(index, comp);
 878             }
 879         }
 880 
 881         invalidateIfValid();
 882         if (peer != null) {
 883             if (comp.peer == null) { // Remove notify was called or it didn't have peer - create new one
 884                 comp.addNotify();
 885             } else { // Both container and child have peers, it means child peer should be reparented.
 886                 // In both cases we need to reparent native widgets.
 887                 Container newNativeContainer = getHeavyweightContainer();
 888                 Container oldNativeContainer = curParent.getHeavyweightContainer();
 889                 if (oldNativeContainer != newNativeContainer) {
 890                     // Native container changed - need to reparent native widgets
 891                     newNativeContainer.reparentChild(comp);
 892                 }
 893                 comp.updateZOrder();
 894 
 895                 if (!comp.isLightweight() && isLightweight()) {
 896                     // If component is heavyweight and one of the containers is lightweight
 897                     // the location of the component should be fixed.
 898                     comp.relocateComponent();
 899                 }
 900             }
 901         }
 902         if (curParent != this) {
 903             /* Notify the layout manager of the added component. */
 904             if (layoutMgr != null) {
 905                 if (layoutMgr instanceof LayoutManager2) {
 906                     ((LayoutManager2)layoutMgr).addLayoutComponent(comp, null);
 907                 } else {
 908                     layoutMgr.addLayoutComponent(null, comp);
 909                 }
 910             }
 911             if (containerListener != null ||
 912                 (eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 ||
 913                 Toolkit.enabledOnToolkit(AWTEvent.CONTAINER_EVENT_MASK)) {
 914                 ContainerEvent e = new ContainerEvent(this,
 915                                                       ContainerEvent.COMPONENT_ADDED,
 916                                                       comp);
 917                 dispatchEvent(e);
 918             }
 919             comp.createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, comp,
 920                                        this, HierarchyEvent.PARENT_CHANGED,
 921                                        Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
 922 
 923             // If component is focus owner or parent container of focus owner check that after reparenting
 924             // focus owner moved out if new container prohibit this kind of focus owner.
 925             if (comp.isFocusOwner() && !comp.canBeFocusOwnerRecursively()) {
 926                 comp.transferFocus();
 927             } else if (comp instanceof Container) {
 928                 Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
 929                 if (focusOwner != null && isParentOf(focusOwner) && !focusOwner.canBeFocusOwnerRecursively()) {
 930                     focusOwner.transferFocus();
 931                 }
 932             }
 933         } else {
 934             comp.createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, comp,
 935                                        this, HierarchyEvent.HIERARCHY_CHANGED,
 936                                        Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
 937         }
 938 
 939         if (peer != null && layoutMgr == null && isVisible()) {
 940             updateCursorImmediately();
 941         }
 942     }
 943 
 944     /**
 945      * Returns the z-order index of the component inside the container.
 946      * The higher a component is in the z-order hierarchy, the lower
 947      * its index.  The component with the lowest z-order index is
 948      * painted last, above all other child components.
 949      *
 950      * @param comp the component being queried
 951      * @return  the z-order index of the component; otherwise
 952      *          returns -1 if the component is {@code null}
 953      *          or doesn't belong to the container
 954      * @see #setComponentZOrder(java.awt.Component, int)
 955      * @since 1.5
 956      */
 957     public int getComponentZOrder(Component comp) {
 958         if (comp == null) {
 959             return -1;
 960         }
 961         synchronized(getTreeLock()) {
 962             // Quick check - container should be immediate parent of the component
 963             if (comp.parent != this) {
 964                 return -1;
 965             }
 966             return component.indexOf(comp);
 967         }
 968     }
 969 
 970     /**
 971      * Adds the specified component to the end of this container.
 972      * Also notifies the layout manager to add the component to
 973      * this container's layout using the specified constraints object.
 974      * This is a convenience method for {@link #addImpl}.
 975      * <p>
 976      * This method changes layout-related information, and therefore,
 977      * invalidates the component hierarchy. If the container has already been
 978      * displayed, the hierarchy must be validated thereafter in order to
 979      * display the added component.
 980      *
 981      *
 982      * @param     comp the component to be added
 983      * @param     constraints an object expressing
 984      *                  layout constraints for this component
 985      * @exception NullPointerException if {@code comp} is {@code null}
 986      * @see #addImpl
 987      * @see #invalidate
 988      * @see #validate
 989      * @see javax.swing.JComponent#revalidate()
 990      * @see       LayoutManager
 991      * @since     1.1
 992      */
 993     public void add(Component comp, Object constraints) {
 994         addImpl(comp, constraints, -1);
 995     }
 996 
 997     /**
 998      * Adds the specified component to this container with the specified
 999      * constraints at the specified index.  Also notifies the layout
1000      * manager to add the component to the this container's layout using
1001      * the specified constraints object.
1002      * This is a convenience method for {@link #addImpl}.
1003      * <p>
1004      * This method changes layout-related information, and therefore,
1005      * invalidates the component hierarchy. If the container has already been
1006      * displayed, the hierarchy must be validated thereafter in order to
1007      * display the added component.
1008      *
1009      *
1010      * @param comp the component to be added
1011      * @param constraints an object expressing layout constraints for this
1012      * @param index the position in the container's list at which to insert
1013      * the component; {@code -1} means insert at the end
1014      * component
1015      * @exception NullPointerException if {@code comp} is {@code null}
1016      * @exception IllegalArgumentException if {@code index} is invalid (see
1017      *            {@link #addImpl} for details)
1018      * @see #addImpl
1019      * @see #invalidate
1020      * @see #validate
1021      * @see javax.swing.JComponent#revalidate()
1022      * @see #remove
1023      * @see LayoutManager
1024      */
1025     public void add(Component comp, Object constraints, int index) {
1026        addImpl(comp, constraints, index);
1027     }
1028 
1029     /**
1030      * Adds the specified component to this container at the specified
1031      * index. This method also notifies the layout manager to add
1032      * the component to this container's layout using the specified
1033      * constraints object via the {@code addLayoutComponent}
1034      * method.
1035      * <p>
1036      * The constraints are
1037      * defined by the particular layout manager being used.  For
1038      * example, the {@code BorderLayout} class defines five
1039      * constraints: {@code BorderLayout.NORTH},
1040      * {@code BorderLayout.SOUTH}, {@code BorderLayout.EAST},
1041      * {@code BorderLayout.WEST}, and {@code BorderLayout.CENTER}.
1042      * <p>
1043      * The {@code GridBagLayout} class requires a
1044      * {@code GridBagConstraints} object.  Failure to pass
1045      * the correct type of constraints object results in an
1046      * {@code IllegalArgumentException}.
1047      * <p>
1048      * If the current layout manager implements {@code LayoutManager2}, then
1049      * {@link LayoutManager2#addLayoutComponent(Component,Object)} is invoked on
1050      * it. If the current layout manager does not implement
1051      * {@code LayoutManager2}, and constraints is a {@code String}, then
1052      * {@link LayoutManager#addLayoutComponent(String,Component)} is invoked on it.
1053      * <p>
1054      * If the component is not an ancestor of this container and has a non-null
1055      * parent, it is removed from its current parent before it is added to this
1056      * container.
1057      * <p>
1058      * This is the method to override if a program needs to track
1059      * every add request to a container as all other add methods defer
1060      * to this one. An overriding method should
1061      * usually include a call to the superclass's version of the method:
1062      *
1063      * <blockquote>
1064      * {@code super.addImpl(comp, constraints, index)}
1065      * </blockquote>
1066      * <p>
1067      * This method changes layout-related information, and therefore,
1068      * invalidates the component hierarchy. If the container has already been
1069      * displayed, the hierarchy must be validated thereafter in order to
1070      * display the added component.
1071      *
1072      * @param     comp       the component to be added
1073      * @param     constraints an object expressing layout constraints
1074      *                 for this component
1075      * @param     index the position in the container's list at which to
1076      *                 insert the component, where {@code -1}
1077      *                 means append to the end
1078      * @exception IllegalArgumentException if {@code index} is invalid;
1079      *            if {@code comp} is a child of this container, the valid
1080      *            range is {@code [-1, getComponentCount()-1]}; if component is
1081      *            not a child of this container, the valid range is
1082      *            {@code [-1, getComponentCount()]}
1083      *
1084      * @exception IllegalArgumentException if {@code comp} is an ancestor of
1085      *                                     this container
1086      * @exception IllegalArgumentException if adding a window to a container
1087      * @exception NullPointerException if {@code comp} is {@code null}
1088      * @see       #add(Component)
1089      * @see       #add(Component, int)
1090      * @see       #add(Component, java.lang.Object)
1091      * @see #invalidate
1092      * @see       LayoutManager
1093      * @see       LayoutManager2
1094      * @since     1.1
1095      */
1096     protected void addImpl(Component comp, Object constraints, int index) {
1097         synchronized (getTreeLock()) {
1098             /* Check for correct arguments:  index in bounds,
1099              * comp cannot be one of this container's parents,
1100              * and comp cannot be a window.
1101              * comp and container must be on the same GraphicsDevice.
1102              * if comp is container, all sub-components must be on
1103              * same GraphicsDevice.
1104              */
1105             GraphicsConfiguration thisGC = this.getGraphicsConfiguration();
1106 
1107             if (index > component.size() || (index < 0 && index != -1)) {
1108                 throw new IllegalArgumentException(
1109                           "illegal component position");
1110             }
1111             checkAddToSelf(comp);
1112             checkNotAWindow(comp);
1113             /* Reparent the component and tidy up the tree's state. */
1114             if (comp.parent != null) {
1115                 comp.parent.remove(comp);
1116                 if (index > component.size()) {
1117                     throw new IllegalArgumentException("illegal component position");
1118                 }
1119             }
1120             if (thisGC != null) {
1121                 comp.checkGD(thisGC.getDevice().getIDstring());
1122             }
1123 
1124 
1125 
1126             //index == -1 means add to the end.
1127             if (index == -1) {
1128                 component.add(comp);
1129             } else {
1130                 component.add(index, comp);
1131             }
1132             comp.parent = this;
1133             comp.setGraphicsConfiguration(thisGC);
1134 
1135             adjustListeningChildren(AWTEvent.HIERARCHY_EVENT_MASK,
1136                 comp.numListening(AWTEvent.HIERARCHY_EVENT_MASK));
1137             adjustListeningChildren(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK,
1138                 comp.numListening(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
1139             adjustDescendants(comp.countHierarchyMembers());
1140 
1141             invalidateIfValid();
1142             if (peer != null) {
1143                 comp.addNotify();
1144             }
1145 
1146             /* Notify the layout manager of the added component. */
1147             if (layoutMgr != null) {
1148                 if (layoutMgr instanceof LayoutManager2) {
1149                     ((LayoutManager2)layoutMgr).addLayoutComponent(comp, constraints);
1150                 } else if (constraints instanceof String) {
1151                     layoutMgr.addLayoutComponent((String)constraints, comp);
1152                 }
1153             }
1154             if (containerListener != null ||
1155                 (eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 ||
1156                 Toolkit.enabledOnToolkit(AWTEvent.CONTAINER_EVENT_MASK)) {
1157                 ContainerEvent e = new ContainerEvent(this,
1158                                      ContainerEvent.COMPONENT_ADDED,
1159                                      comp);
1160                 dispatchEvent(e);
1161             }
1162 
1163             comp.createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, comp,
1164                                        this, HierarchyEvent.PARENT_CHANGED,
1165                                        Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
1166             if (peer != null && layoutMgr == null && isVisible()) {
1167                 updateCursorImmediately();
1168             }
1169         }
1170     }
1171 
1172     @Override
1173     boolean updateGraphicsData(GraphicsConfiguration gc) {
1174         checkTreeLock();
1175 
1176         boolean ret = super.updateGraphicsData(gc);
1177 
1178         for (Component comp : component) {
1179             if (comp != null) {
1180                 ret |= comp.updateGraphicsData(gc);
1181             }
1182         }
1183         return ret;
1184     }
1185 
1186     /**
1187      * Checks that all Components that this Container contains are on
1188      * the same GraphicsDevice as this Container.  If not, throws an
1189      * IllegalArgumentException.
1190      */
1191     void checkGD(String stringID) {
1192         for (Component comp : component) {
1193             if (comp != null) {
1194                 comp.checkGD(stringID);
1195             }
1196         }
1197     }
1198 
1199     /**
1200      * Removes the component, specified by {@code index},
1201      * from this container.
1202      * This method also notifies the layout manager to remove the
1203      * component from this container's layout via the
1204      * {@code removeLayoutComponent} method.
1205      * <p>
1206      * This method changes layout-related information, and therefore,
1207      * invalidates the component hierarchy. If the container has already been
1208      * displayed, the hierarchy must be validated thereafter in order to
1209      * reflect the changes.
1210      *
1211      *
1212      * @param     index   the index of the component to be removed
1213      * @throws ArrayIndexOutOfBoundsException if {@code index} is not in
1214      *         range {@code [0, getComponentCount()-1]}
1215      * @see #add
1216      * @see #invalidate
1217      * @see #validate
1218      * @see #getComponentCount
1219      * @since 1.1
1220      */
1221     public void remove(int index) {
1222         synchronized (getTreeLock()) {
1223             if (index < 0  || index >= component.size()) {
1224                 throw new ArrayIndexOutOfBoundsException(index);
1225             }
1226             Component comp = component.get(index);
1227             if (peer != null) {
1228                 comp.removeNotify();
1229             }
1230             if (layoutMgr != null) {
1231                 layoutMgr.removeLayoutComponent(comp);
1232             }
1233 
1234             adjustListeningChildren(AWTEvent.HIERARCHY_EVENT_MASK,
1235                 -comp.numListening(AWTEvent.HIERARCHY_EVENT_MASK));
1236             adjustListeningChildren(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK,
1237                 -comp.numListening(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
1238             adjustDescendants(-(comp.countHierarchyMembers()));
1239 
1240             comp.parent = null;
1241             component.remove(index);
1242             comp.setGraphicsConfiguration(null);
1243 
1244             invalidateIfValid();
1245             if (containerListener != null ||
1246                 (eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 ||
1247                 Toolkit.enabledOnToolkit(AWTEvent.CONTAINER_EVENT_MASK)) {
1248                 ContainerEvent e = new ContainerEvent(this,
1249                                      ContainerEvent.COMPONENT_REMOVED,
1250                                      comp);
1251                 dispatchEvent(e);
1252             }
1253 
1254             comp.createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, comp,
1255                                        this, HierarchyEvent.PARENT_CHANGED,
1256                                        Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
1257             if (peer != null && layoutMgr == null && isVisible()) {
1258                 updateCursorImmediately();
1259             }
1260         }
1261     }
1262 
1263     /**
1264      * Removes the specified component from this container.
1265      * This method also notifies the layout manager to remove the
1266      * component from this container's layout via the
1267      * {@code removeLayoutComponent} method.
1268      * <p>
1269      * This method changes layout-related information, and therefore,
1270      * invalidates the component hierarchy. If the container has already been
1271      * displayed, the hierarchy must be validated thereafter in order to
1272      * reflect the changes.
1273      *
1274      * @param comp the component to be removed
1275      * @throws NullPointerException if {@code comp} is {@code null}
1276      * @see #add
1277      * @see #invalidate
1278      * @see #validate
1279      * @see #remove(int)
1280      */
1281     public void remove(Component comp) {
1282         synchronized (getTreeLock()) {
1283             if (comp.parent == this)  {
1284                 int index = component.indexOf(comp);
1285                 if (index >= 0) {
1286                     remove(index);
1287                 }
1288             }
1289         }
1290     }
1291 
1292     /**
1293      * Removes all the components from this container.
1294      * This method also notifies the layout manager to remove the
1295      * components from this container's layout via the
1296      * {@code removeLayoutComponent} method.
1297      * <p>
1298      * This method changes layout-related information, and therefore,
1299      * invalidates the component hierarchy. If the container has already been
1300      * displayed, the hierarchy must be validated thereafter in order to
1301      * reflect the changes.
1302      *
1303      * @see #add
1304      * @see #remove
1305      * @see #invalidate
1306      */
1307     public void removeAll() {
1308         synchronized (getTreeLock()) {
1309             adjustListeningChildren(AWTEvent.HIERARCHY_EVENT_MASK,
1310                                     -listeningChildren);
1311             adjustListeningChildren(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK,
1312                                     -listeningBoundsChildren);
1313             adjustDescendants(-descendantsCount);
1314 
1315             while (!component.isEmpty()) {
1316                 Component comp = component.remove(component.size()-1);
1317 
1318                 if (peer != null) {
1319                     comp.removeNotify();
1320                 }
1321                 if (layoutMgr != null) {
1322                     layoutMgr.removeLayoutComponent(comp);
1323                 }
1324                 comp.parent = null;
1325                 comp.setGraphicsConfiguration(null);
1326                 if (containerListener != null ||
1327                    (eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 ||
1328                     Toolkit.enabledOnToolkit(AWTEvent.CONTAINER_EVENT_MASK)) {
1329                     ContainerEvent e = new ContainerEvent(this,
1330                                      ContainerEvent.COMPONENT_REMOVED,
1331                                      comp);
1332                     dispatchEvent(e);
1333                 }
1334 
1335                 comp.createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,
1336                                            comp, this,
1337                                            HierarchyEvent.PARENT_CHANGED,
1338                                            Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
1339             }
1340             if (peer != null && layoutMgr == null && isVisible()) {
1341                 updateCursorImmediately();
1342             }
1343             invalidateIfValid();
1344         }
1345     }
1346 
1347     // Should only be called while holding tree lock
1348     int numListening(long mask) {
1349         int superListening = super.numListening(mask);
1350 
1351         if (mask == AWTEvent.HIERARCHY_EVENT_MASK) {
1352             if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
1353                 // Verify listeningChildren is correct
1354                 int sum = 0;
1355                 for (Component comp : component) {
1356                     sum += comp.numListening(mask);
1357                 }
1358                 if (listeningChildren != sum) {
1359                     eventLog.fine("Assertion (listeningChildren == sum) failed");
1360                 }
1361             }
1362             return listeningChildren + superListening;
1363         } else if (mask == AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) {
1364             if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
1365                 // Verify listeningBoundsChildren is correct
1366                 int sum = 0;
1367                 for (Component comp : component) {
1368                     sum += comp.numListening(mask);
1369                 }
1370                 if (listeningBoundsChildren != sum) {
1371                     eventLog.fine("Assertion (listeningBoundsChildren == sum) failed");
1372                 }
1373             }
1374             return listeningBoundsChildren + superListening;
1375         } else {
1376             // assert false;
1377             if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
1378                 eventLog.fine("This code must never be reached");
1379             }
1380             return superListening;
1381         }
1382     }
1383 
1384     // Should only be called while holding tree lock
1385     void adjustListeningChildren(long mask, int num) {
1386         if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
1387             boolean toAssert = (mask == AWTEvent.HIERARCHY_EVENT_MASK ||
1388                                 mask == AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK ||
1389                                 mask == (AWTEvent.HIERARCHY_EVENT_MASK |
1390                                          AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
1391             if (!toAssert) {
1392                 eventLog.fine("Assertion failed");
1393             }
1394         }
1395 
1396         if (num == 0)
1397             return;
1398 
1399         if ((mask & AWTEvent.HIERARCHY_EVENT_MASK) != 0) {
1400             listeningChildren += num;
1401         }
1402         if ((mask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0) {
1403             listeningBoundsChildren += num;
1404         }
1405 
1406         adjustListeningChildrenOnParent(mask, num);
1407     }
1408 
1409     // Should only be called while holding tree lock
1410     void adjustDescendants(int num) {
1411         if (num == 0)
1412             return;
1413 
1414         descendantsCount += num;
1415         adjustDescendantsOnParent(num);
1416     }
1417 
1418     // Should only be called while holding tree lock
1419     void adjustDescendantsOnParent(int num) {
1420         if (parent != null) {
1421             parent.adjustDescendants(num);
1422         }
1423     }
1424 
1425     // Should only be called while holding tree lock
1426     int countHierarchyMembers() {
1427         if (log.isLoggable(PlatformLogger.Level.FINE)) {
1428             // Verify descendantsCount is correct
1429             int sum = 0;
1430             for (Component comp : component) {
1431                 sum += comp.countHierarchyMembers();
1432             }
1433             if (descendantsCount != sum) {
1434                 log.fine("Assertion (descendantsCount == sum) failed");
1435             }
1436         }
1437         return descendantsCount + 1;
1438     }
1439 
1440     private int getListenersCount(int id, boolean enabledOnToolkit) {
1441         checkTreeLock();
1442         if (enabledOnToolkit) {
1443             return descendantsCount;
1444         }
1445         switch (id) {
1446           case HierarchyEvent.HIERARCHY_CHANGED:
1447             return listeningChildren;
1448           case HierarchyEvent.ANCESTOR_MOVED:
1449           case HierarchyEvent.ANCESTOR_RESIZED:
1450             return listeningBoundsChildren;
1451           default:
1452             return 0;
1453         }
1454     }
1455 
1456     final int createHierarchyEvents(int id, Component changed,
1457         Container changedParent, long changeFlags, boolean enabledOnToolkit)
1458     {
1459         checkTreeLock();
1460         int listeners = getListenersCount(id, enabledOnToolkit);
1461 
1462         for (int count = listeners, i = 0; count > 0; i++) {
1463             count -= component.get(i).createHierarchyEvents(id, changed,
1464                 changedParent, changeFlags, enabledOnToolkit);
1465         }
1466         return listeners +
1467             super.createHierarchyEvents(id, changed, changedParent,
1468                                         changeFlags, enabledOnToolkit);
1469     }
1470 
1471     final void createChildHierarchyEvents(int id, long changeFlags,
1472         boolean enabledOnToolkit)
1473     {
1474         checkTreeLock();
1475         if (component.isEmpty()) {
1476             return;
1477         }
1478         int listeners = getListenersCount(id, enabledOnToolkit);
1479 
1480         for (int count = listeners, i = 0; count > 0; i++) {
1481             count -= component.get(i).createHierarchyEvents(id, this, parent,
1482                 changeFlags, enabledOnToolkit);
1483         }
1484     }
1485 
1486     /**
1487      * Gets the layout manager for this container.
1488      *
1489      * @see #doLayout
1490      * @see #setLayout
1491      * @return the current layout manager for this container
1492      */
1493     public LayoutManager getLayout() {
1494         return layoutMgr;
1495     }
1496 
1497     /**
1498      * Sets the layout manager for this container.
1499      * <p>
1500      * This method changes layout-related information, and therefore,
1501      * invalidates the component hierarchy.
1502      *
1503      * @param mgr the specified layout manager
1504      * @see #doLayout
1505      * @see #getLayout
1506      * @see #invalidate
1507      */
1508     public void setLayout(LayoutManager mgr) {
1509         layoutMgr = mgr;
1510         invalidateIfValid();
1511     }
1512 
1513     /**
1514      * Causes this container to lay out its components.  Most programs
1515      * should not call this method directly, but should invoke
1516      * the {@code validate} method instead.
1517      * @see LayoutManager#layoutContainer
1518      * @see #setLayout
1519      * @see #validate
1520      * @since 1.1
1521      */
1522     public void doLayout() {
1523         layout();
1524     }
1525 
1526     /**
1527      * @deprecated As of JDK version 1.1,
1528      * replaced by {@code doLayout()}.
1529      */
1530     @Deprecated
1531     public void layout() {
1532         LayoutManager layoutMgr = this.layoutMgr;
1533         if (layoutMgr != null) {
1534             layoutMgr.layoutContainer(this);
1535         }
1536     }
1537 
1538     /**
1539      * Indicates if this container is a <i>validate root</i>.
1540      * <p>
1541      * Layout-related changes, such as bounds of the validate root descendants,
1542      * do not affect the layout of the validate root parent. This peculiarity
1543      * enables the {@code invalidate()} method to stop invalidating the
1544      * component hierarchy when the method encounters a validate root. However,
1545      * to preserve backward compatibility this new optimized behavior is
1546      * enabled only when the {@code java.awt.smartInvalidate} system property
1547      * value is set to {@code true}.
1548      * <p>
1549      * If a component hierarchy contains validate roots and the new optimized
1550      * {@code invalidate()} behavior is enabled, the {@code validate()} method
1551      * must be invoked on the validate root of a previously invalidated
1552      * component to restore the validity of the hierarchy later. Otherwise,
1553      * calling the {@code validate()} method on the top-level container (such
1554      * as a {@code Frame} object) should be used to restore the validity of the
1555      * component hierarchy.
1556      * <p>
1557      * The {@code Window} class and the {@code Applet} class are the validate
1558      * roots in AWT.  Swing introduces more validate roots.
1559      *
1560      * @return whether this container is a validate root
1561      * @see #invalidate
1562      * @see java.awt.Component#invalidate
1563      * @see javax.swing.JComponent#isValidateRoot
1564      * @see javax.swing.JComponent#revalidate
1565      * @since 1.7
1566      */
1567     public boolean isValidateRoot() {
1568         return false;
1569     }
1570 
1571     private static final boolean isJavaAwtSmartInvalidate;
1572     static {
1573         // Don't lazy-read because every app uses invalidate()
1574         isJavaAwtSmartInvalidate = AccessController.doPrivileged(
1575                 new GetBooleanAction("java.awt.smartInvalidate"));
1576     }
1577 
1578     /**
1579      * Invalidates the parent of the container unless the container
1580      * is a validate root.
1581      */
1582     @Override
1583     void invalidateParent() {
1584         if (!isJavaAwtSmartInvalidate || !isValidateRoot()) {
1585             super.invalidateParent();
1586         }
1587     }
1588 
1589     /**
1590      * Invalidates the container.
1591      * <p>
1592      * If the {@code LayoutManager} installed on this container is an instance
1593      * of the {@code LayoutManager2} interface, then
1594      * the {@link LayoutManager2#invalidateLayout(Container)} method is invoked
1595      * on it supplying this {@code Container} as the argument.
1596      * <p>
1597      * Afterwards this method marks this container invalid, and invalidates its
1598      * ancestors. See the {@link Component#invalidate} method for more details.
1599      *
1600      * @see #validate
1601      * @see #layout
1602      * @see LayoutManager2
1603      */
1604     @Override
1605     public void invalidate() {
1606         LayoutManager layoutMgr = this.layoutMgr;
1607         if (layoutMgr instanceof LayoutManager2) {
1608             LayoutManager2 lm = (LayoutManager2) layoutMgr;
1609             lm.invalidateLayout(this);
1610         }
1611         super.invalidate();
1612     }
1613 
1614     /**
1615      * Validates this container and all of its subcomponents.
1616      * <p>
1617      * Validating a container means laying out its subcomponents.
1618      * Layout-related changes, such as setting the bounds of a component, or
1619      * adding a component to the container, invalidate the container
1620      * automatically.  Note that the ancestors of the container may be
1621      * invalidated also (see {@link Component#invalidate} for details.)
1622      * Therefore, to restore the validity of the hierarchy, the {@code
1623      * validate()} method should be invoked on the top-most invalid
1624      * container of the hierarchy.
1625      * <p>
1626      * Validating the container may be a quite time-consuming operation. For
1627      * performance reasons a developer may postpone the validation of the
1628      * hierarchy till a set of layout-related operations completes, e.g. after
1629      * adding all the children to the container.
1630      * <p>
1631      * If this {@code Container} is not valid, this method invokes
1632      * the {@code validateTree} method and marks this {@code Container}
1633      * as valid. Otherwise, no action is performed.
1634      *
1635      * @see #add(java.awt.Component)
1636      * @see #invalidate
1637      * @see Container#isValidateRoot
1638      * @see javax.swing.JComponent#revalidate()
1639      * @see #validateTree
1640      */
1641     public void validate() {
1642         boolean updateCur = false;
1643         synchronized (getTreeLock()) {
1644             if ((!isValid() || descendUnconditionallyWhenValidating)
1645                     && peer != null)
1646             {
1647                 ContainerPeer p = null;
1648                 if (peer instanceof ContainerPeer) {
1649                     p = (ContainerPeer) peer;
1650                 }
1651                 if (p != null) {
1652                     p.beginValidate();
1653                 }
1654                 validateTree();
1655                 if (p != null) {
1656                     p.endValidate();
1657                     // Avoid updating cursor if this is an internal call.
1658                     // See validateUnconditionally() for details.
1659                     if (!descendUnconditionallyWhenValidating) {
1660                         updateCur = isVisible();
1661                     }
1662                 }
1663             }
1664         }
1665         if (updateCur) {
1666             updateCursorImmediately();
1667         }
1668     }
1669 
1670     /**
1671      * Indicates whether valid containers should also traverse their
1672      * children and call the validateTree() method on them.
1673      *
1674      * Synchronization: TreeLock.
1675      *
1676      * The field is allowed to be static as long as the TreeLock itself is
1677      * static.
1678      *
1679      * @see #validateUnconditionally()
1680      */
1681     private static boolean descendUnconditionallyWhenValidating = false;
1682 
1683     /**
1684      * Unconditionally validate the component hierarchy.
1685      */
1686     final void validateUnconditionally() {
1687         boolean updateCur = false;
1688         synchronized (getTreeLock()) {
1689             descendUnconditionallyWhenValidating = true;
1690 
1691             validate();
1692             if (peer instanceof ContainerPeer) {
1693                 updateCur = isVisible();
1694             }
1695 
1696             descendUnconditionallyWhenValidating = false;
1697         }
1698         if (updateCur) {
1699             updateCursorImmediately();
1700         }
1701     }
1702 
1703     /**
1704      * Recursively descends the container tree and recomputes the
1705      * layout for any subtrees marked as needing it (those marked as
1706      * invalid).  Synchronization should be provided by the method
1707      * that calls this one:  {@code validate}.
1708      *
1709      * @see #doLayout
1710      * @see #validate
1711      */
1712     protected void validateTree() {
1713         checkTreeLock();
1714         if (!isValid() || descendUnconditionallyWhenValidating) {
1715             if (peer instanceof ContainerPeer) {
1716                 ((ContainerPeer)peer).beginLayout();
1717             }
1718             if (!isValid()) {
1719                 doLayout();
1720             }
1721             for (int i = 0; i < component.size(); i++) {
1722                 Component comp = component.get(i);
1723                 if (   (comp instanceof Container)
1724                        && !(comp instanceof Window)
1725                        && (!comp.isValid() ||
1726                            descendUnconditionallyWhenValidating))
1727                 {
1728                     ((Container)comp).validateTree();
1729                 } else {
1730                     comp.validate();
1731                 }
1732             }
1733             if (peer instanceof ContainerPeer) {
1734                 ((ContainerPeer)peer).endLayout();
1735             }
1736         }
1737         super.validate();
1738     }
1739 
1740     /**
1741      * Recursively descends the container tree and invalidates all
1742      * contained components.
1743      */
1744     void invalidateTree() {
1745         synchronized (getTreeLock()) {
1746             for (int i = 0; i < component.size(); i++) {
1747                 Component comp = component.get(i);
1748                 if (comp instanceof Container) {
1749                     ((Container)comp).invalidateTree();
1750                 }
1751                 else {
1752                     comp.invalidateIfValid();
1753                 }
1754             }
1755             invalidateIfValid();
1756         }
1757     }
1758 
1759     /**
1760      * Sets the font of this container.
1761      * <p>
1762      * This method changes layout-related information, and therefore,
1763      * invalidates the component hierarchy.
1764      *
1765      * @param f The font to become this container's font.
1766      * @see Component#getFont
1767      * @see #invalidate
1768      * @since 1.0
1769      */
1770     public void setFont(Font f) {
1771         boolean shouldinvalidate = false;
1772 
1773         Font oldfont = getFont();
1774         super.setFont(f);
1775         Font newfont = getFont();
1776         if (newfont != oldfont && (oldfont == null ||
1777                                    !oldfont.equals(newfont))) {
1778             invalidateTree();
1779         }
1780     }
1781 
1782     /**
1783      * Returns the preferred size of this container.  If the preferred size has
1784      * not been set explicitly by {@link Component#setPreferredSize(Dimension)}
1785      * and this {@code Container} has a {@code non-null} {@link LayoutManager},
1786      * then {@link LayoutManager#preferredLayoutSize(Container)}
1787      * is used to calculate the preferred size.
1788      *
1789      * <p>Note: some implementations may cache the value returned from the
1790      * {@code LayoutManager}.  Implementations that cache need not invoke
1791      * {@code preferredLayoutSize} on the {@code LayoutManager} every time
1792      * this method is invoked, rather the {@code LayoutManager} will only
1793      * be queried after the {@code Container} becomes invalid.
1794      *
1795      * @return    an instance of {@code Dimension} that represents
1796      *                the preferred size of this container.
1797      * @see       #getMinimumSize
1798      * @see       #getMaximumSize
1799      * @see       #getLayout
1800      * @see       LayoutManager#preferredLayoutSize(Container)
1801      * @see       Component#getPreferredSize
1802      */
1803     public Dimension getPreferredSize() {
1804         return preferredSize();
1805     }
1806 
1807     /**
1808      * @deprecated As of JDK version 1.1,
1809      * replaced by {@code getPreferredSize()}.
1810      */
1811     @Deprecated
1812     public Dimension preferredSize() {
1813         /* Avoid grabbing the lock if a reasonable cached size value
1814          * is available.
1815          */
1816         Dimension dim = prefSize;
1817         if (dim == null || !(isPreferredSizeSet() || isValid())) {
1818             synchronized (getTreeLock()) {
1819                 prefSize = (layoutMgr != null) ?
1820                     layoutMgr.preferredLayoutSize(this) :
1821                     super.preferredSize();
1822                 dim = prefSize;
1823             }
1824         }
1825         if (dim != null){
1826             return new Dimension(dim);
1827         }
1828         else{
1829             return dim;
1830         }
1831     }
1832 
1833     /**
1834      * Returns the minimum size of this container.  If the minimum size has
1835      * not been set explicitly by {@link Component#setMinimumSize(Dimension)}
1836      * and this {@code Container} has a {@code non-null} {@link LayoutManager},
1837      * then {@link LayoutManager#minimumLayoutSize(Container)}
1838      * is used to calculate the minimum size.
1839      *
1840      * <p>Note: some implementations may cache the value returned from the
1841      * {@code LayoutManager}.  Implementations that cache need not invoke
1842      * {@code minimumLayoutSize} on the {@code LayoutManager} every time
1843      * this method is invoked, rather the {@code LayoutManager} will only
1844      * be queried after the {@code Container} becomes invalid.
1845      *
1846      * @return    an instance of {@code Dimension} that represents
1847      *                the minimum size of this container.
1848      * @see       #getPreferredSize
1849      * @see       #getMaximumSize
1850      * @see       #getLayout
1851      * @see       LayoutManager#minimumLayoutSize(Container)
1852      * @see       Component#getMinimumSize
1853      * @since     1.1
1854      */
1855     public Dimension getMinimumSize() {
1856         return minimumSize();
1857     }
1858 
1859     /**
1860      * @deprecated As of JDK version 1.1,
1861      * replaced by {@code getMinimumSize()}.
1862      */
1863     @Deprecated
1864     public Dimension minimumSize() {
1865         /* Avoid grabbing the lock if a reasonable cached size value
1866          * is available.
1867          */
1868         Dimension dim = minSize;
1869         if (dim == null || !(isMinimumSizeSet() || isValid())) {
1870             synchronized (getTreeLock()) {
1871                 minSize = (layoutMgr != null) ?
1872                     layoutMgr.minimumLayoutSize(this) :
1873                     super.minimumSize();
1874                 dim = minSize;
1875             }
1876         }
1877         if (dim != null){
1878             return new Dimension(dim);
1879         }
1880         else{
1881             return dim;
1882         }
1883     }
1884 
1885     /**
1886      * Returns the maximum size of this container.  If the maximum size has
1887      * not been set explicitly by {@link Component#setMaximumSize(Dimension)}
1888      * and the {@link LayoutManager} installed on this {@code Container}
1889      * is an instance of {@link LayoutManager2}, then
1890      * {@link LayoutManager2#maximumLayoutSize(Container)}
1891      * is used to calculate the maximum size.
1892      *
1893      * <p>Note: some implementations may cache the value returned from the
1894      * {@code LayoutManager2}.  Implementations that cache need not invoke
1895      * {@code maximumLayoutSize} on the {@code LayoutManager2} every time
1896      * this method is invoked, rather the {@code LayoutManager2} will only
1897      * be queried after the {@code Container} becomes invalid.
1898      *
1899      * @return    an instance of {@code Dimension} that represents
1900      *                the maximum size of this container.
1901      * @see       #getPreferredSize
1902      * @see       #getMinimumSize
1903      * @see       #getLayout
1904      * @see       LayoutManager2#maximumLayoutSize(Container)
1905      * @see       Component#getMaximumSize
1906      */
1907     public Dimension getMaximumSize() {
1908         /* Avoid grabbing the lock if a reasonable cached size value
1909          * is available.
1910          */
1911         Dimension dim = maxSize;
1912         if (dim == null || !(isMaximumSizeSet() || isValid())) {
1913             synchronized (getTreeLock()) {
1914                if (layoutMgr instanceof LayoutManager2) {
1915                     LayoutManager2 lm = (LayoutManager2) layoutMgr;
1916                     maxSize = lm.maximumLayoutSize(this);
1917                } else {
1918                     maxSize = super.getMaximumSize();
1919                }
1920                dim = maxSize;
1921             }
1922         }
1923         if (dim != null){
1924             return new Dimension(dim);
1925         }
1926         else{
1927             return dim;
1928         }
1929     }
1930 
1931     /**
1932      * Returns the alignment along the x axis.  This specifies how
1933      * the component would like to be aligned relative to other
1934      * components.  The value should be a number between 0 and 1
1935      * where 0 represents alignment along the origin, 1 is aligned
1936      * the furthest away from the origin, 0.5 is centered, etc.
1937      */
1938     public float getAlignmentX() {
1939         float xAlign;
1940         if (layoutMgr instanceof LayoutManager2) {
1941             synchronized (getTreeLock()) {
1942                 LayoutManager2 lm = (LayoutManager2) layoutMgr;
1943                 xAlign = lm.getLayoutAlignmentX(this);
1944             }
1945         } else {
1946             xAlign = super.getAlignmentX();
1947         }
1948         return xAlign;
1949     }
1950 
1951     /**
1952      * Returns the alignment along the y axis.  This specifies how
1953      * the component would like to be aligned relative to other
1954      * components.  The value should be a number between 0 and 1
1955      * where 0 represents alignment along the origin, 1 is aligned
1956      * the furthest away from the origin, 0.5 is centered, etc.
1957      */
1958     public float getAlignmentY() {
1959         float yAlign;
1960         if (layoutMgr instanceof LayoutManager2) {
1961             synchronized (getTreeLock()) {
1962                 LayoutManager2 lm = (LayoutManager2) layoutMgr;
1963                 yAlign = lm.getLayoutAlignmentY(this);
1964             }
1965         } else {
1966             yAlign = super.getAlignmentY();
1967         }
1968         return yAlign;
1969     }
1970 
1971     /**
1972      * Paints the container. This forwards the paint to any lightweight
1973      * components that are children of this container. If this method is
1974      * reimplemented, super.paint(g) should be called so that lightweight
1975      * components are properly rendered. If a child component is entirely
1976      * clipped by the current clipping setting in g, paint() will not be
1977      * forwarded to that child.
1978      *
1979      * @param g the specified Graphics window
1980      * @see   Component#update(Graphics)
1981      */
1982     public void paint(Graphics g) {
1983         if (isShowing()) {
1984             synchronized (getObjectLock()) {
1985                 if (printing) {
1986                     if (printingThreads.contains(Thread.currentThread())) {
1987                         return;
1988                     }
1989                 }
1990             }
1991 
1992             // The container is showing on screen and
1993             // this paint() is not called from print().
1994             // Paint self and forward the paint to lightweight subcomponents.
1995 
1996             // super.paint(); -- Don't bother, since it's a NOP.
1997 
1998             GraphicsCallback.PaintCallback.getInstance().
1999                 runComponents(getComponentsSync(), g, GraphicsCallback.LIGHTWEIGHTS);
2000         }
2001     }
2002 
2003     /**
2004      * Updates the container.  This forwards the update to any lightweight
2005      * components that are children of this container.  If this method is
2006      * reimplemented, super.update(g) should be called so that lightweight
2007      * components are properly rendered.  If a child component is entirely
2008      * clipped by the current clipping setting in g, update() will not be
2009      * forwarded to that child.
2010      *
2011      * @param g the specified Graphics window
2012      * @see   Component#update(Graphics)
2013      */
2014     public void update(Graphics g) {
2015         if (isShowing()) {
2016             if (! (peer instanceof LightweightPeer)) {
2017                 g.clearRect(0, 0, width, height);
2018             }
2019             paint(g);
2020         }
2021     }
2022 
2023     /**
2024      * Prints the container. This forwards the print to any lightweight
2025      * components that are children of this container. If this method is
2026      * reimplemented, super.print(g) should be called so that lightweight
2027      * components are properly rendered. If a child component is entirely
2028      * clipped by the current clipping setting in g, print() will not be
2029      * forwarded to that child.
2030      *
2031      * @param g the specified Graphics window
2032      * @see   Component#update(Graphics)
2033      */
2034     public void print(Graphics g) {
2035         if (isShowing()) {
2036             Thread t = Thread.currentThread();
2037             try {
2038                 synchronized (getObjectLock()) {
2039                     if (printingThreads == null) {
2040                         printingThreads = new HashSet<>();
2041                     }
2042                     printingThreads.add(t);
2043                     printing = true;
2044                 }
2045                 super.print(g);  // By default, Component.print() calls paint()
2046             } finally {
2047                 synchronized (getObjectLock()) {
2048                     printingThreads.remove(t);
2049                     printing = !printingThreads.isEmpty();
2050                 }
2051             }
2052 
2053             GraphicsCallback.PrintCallback.getInstance().
2054                 runComponents(getComponentsSync(), g, GraphicsCallback.LIGHTWEIGHTS);
2055         }
2056     }
2057 
2058     /**
2059      * Paints each of the components in this container.
2060      * @param     g   the graphics context.
2061      * @see       Component#paint
2062      * @see       Component#paintAll
2063      */
2064     public void paintComponents(Graphics g) {
2065         if (isShowing()) {
2066             GraphicsCallback.PaintAllCallback.getInstance().
2067                 runComponents(getComponentsSync(), g, GraphicsCallback.TWO_PASSES);
2068         }
2069     }
2070 
2071     /**
2072      * Simulates the peer callbacks into java.awt for printing of
2073      * lightweight Containers.
2074      * @param     g   the graphics context to use for printing.
2075      * @see       Component#printAll
2076      * @see       #printComponents
2077      */
2078     void lightweightPaint(Graphics g) {
2079         super.lightweightPaint(g);
2080         paintHeavyweightComponents(g);
2081     }
2082 
2083     /**
2084      * Prints all the heavyweight subcomponents.
2085      */
2086     void paintHeavyweightComponents(Graphics g) {
2087         if (isShowing()) {
2088             GraphicsCallback.PaintHeavyweightComponentsCallback.getInstance().
2089                 runComponents(getComponentsSync(), g,
2090                               GraphicsCallback.LIGHTWEIGHTS | GraphicsCallback.HEAVYWEIGHTS);
2091         }
2092     }
2093 
2094     /**
2095      * Prints each of the components in this container.
2096      * @param     g   the graphics context.
2097      * @see       Component#print
2098      * @see       Component#printAll
2099      */
2100     public void printComponents(Graphics g) {
2101         if (isShowing()) {
2102             GraphicsCallback.PrintAllCallback.getInstance().
2103                 runComponents(getComponentsSync(), g, GraphicsCallback.TWO_PASSES);
2104         }
2105     }
2106 
2107     /**
2108      * Simulates the peer callbacks into java.awt for printing of
2109      * lightweight Containers.
2110      * @param     g   the graphics context to use for printing.
2111      * @see       Component#printAll
2112      * @see       #printComponents
2113      */
2114     void lightweightPrint(Graphics g) {
2115         super.lightweightPrint(g);
2116         printHeavyweightComponents(g);
2117     }
2118 
2119     /**
2120      * Prints all the heavyweight subcomponents.
2121      */
2122     void printHeavyweightComponents(Graphics g) {
2123         if (isShowing()) {
2124             GraphicsCallback.PrintHeavyweightComponentsCallback.getInstance().
2125                 runComponents(getComponentsSync(), g,
2126                               GraphicsCallback.LIGHTWEIGHTS | GraphicsCallback.HEAVYWEIGHTS);
2127         }
2128     }
2129 
2130     /**
2131      * Adds the specified container listener to receive container events
2132      * from this container.
2133      * If l is null, no exception is thrown and no action is performed.
2134      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
2135      * >AWT Threading Issues</a> for details on AWT's threading model.
2136      *
2137      * @param    l the container listener
2138      *
2139      * @see #removeContainerListener
2140      * @see #getContainerListeners
2141      */
2142     public synchronized void addContainerListener(ContainerListener l) {
2143         if (l == null) {
2144             return;
2145         }
2146         containerListener = AWTEventMulticaster.add(containerListener, l);
2147         newEventsOnly = true;
2148     }
2149 
2150     /**
2151      * Removes the specified container listener so it no longer receives
2152      * container events from this container.
2153      * If l is null, no exception is thrown and no action is performed.
2154      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
2155      * >AWT Threading Issues</a> for details on AWT's threading model.
2156      *
2157      * @param   l the container listener
2158      *
2159      * @see #addContainerListener
2160      * @see #getContainerListeners
2161      */
2162     public synchronized void removeContainerListener(ContainerListener l) {
2163         if (l == null) {
2164             return;
2165         }
2166         containerListener = AWTEventMulticaster.remove(containerListener, l);
2167     }
2168 
2169     /**
2170      * Returns an array of all the container listeners
2171      * registered on this container.
2172      *
2173      * @return all of this container's {@code ContainerListener}s
2174      *         or an empty array if no container
2175      *         listeners are currently registered
2176      *
2177      * @see #addContainerListener
2178      * @see #removeContainerListener
2179      * @since 1.4
2180      */
2181     public synchronized ContainerListener[] getContainerListeners() {
2182         return getListeners(ContainerListener.class);
2183     }
2184 
2185     /**
2186      * Returns an array of all the objects currently registered
2187      * as <code><em>Foo</em>Listener</code>s
2188      * upon this {@code Container}.
2189      * <code><em>Foo</em>Listener</code>s are registered using the
2190      * <code>add<em>Foo</em>Listener</code> method.
2191      *
2192      * <p>
2193      * You can specify the {@code listenerType} argument
2194      * with a class literal, such as
2195      * <code><em>Foo</em>Listener.class</code>.
2196      * For example, you can query a
2197      * {@code Container c}
2198      * for its container listeners with the following code:
2199      *
2200      * <pre>ContainerListener[] cls = (ContainerListener[])(c.getListeners(ContainerListener.class));</pre>
2201      *
2202      * If no such listeners exist, this method returns an empty array.
2203      *
2204      * @param listenerType the type of listeners requested; this parameter
2205      *          should specify an interface that descends from
2206      *          {@code java.util.EventListener}
2207      * @return an array of all objects registered as
2208      *          <code><em>Foo</em>Listener</code>s on this container,
2209      *          or an empty array if no such listeners have been added
2210      * @exception ClassCastException if {@code listenerType}
2211      *          doesn't specify a class or interface that implements
2212      *          {@code java.util.EventListener}
2213      * @exception NullPointerException if {@code listenerType} is {@code null}
2214      *
2215      * @see #getContainerListeners
2216      *
2217      * @since 1.3
2218      */
2219     public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
2220         EventListener l = null;
2221         if  (listenerType == ContainerListener.class) {
2222             l = containerListener;
2223         } else {
2224             return super.getListeners(listenerType);
2225         }
2226         return AWTEventMulticaster.getListeners(l, listenerType);
2227     }
2228 
2229     // REMIND: remove when filtering is done at lower level
2230     boolean eventEnabled(AWTEvent e) {
2231         int id = e.getID();
2232 
2233         if (id == ContainerEvent.COMPONENT_ADDED ||
2234             id == ContainerEvent.COMPONENT_REMOVED) {
2235             if ((eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 ||
2236                 containerListener != null) {
2237                 return true;
2238             }
2239             return false;
2240         }
2241         return super.eventEnabled(e);
2242     }
2243 
2244     /**
2245      * Processes events on this container. If the event is a
2246      * {@code ContainerEvent}, it invokes the
2247      * {@code processContainerEvent} method, else it invokes
2248      * its superclass's {@code processEvent}.
2249      * <p>Note that if the event parameter is {@code null}
2250      * the behavior is unspecified and may result in an
2251      * exception.
2252      *
2253      * @param e the event
2254      */
2255     protected void processEvent(AWTEvent e) {
2256         if (e instanceof ContainerEvent) {
2257             processContainerEvent((ContainerEvent)e);
2258             return;
2259         }
2260         super.processEvent(e);
2261     }
2262 
2263     /**
2264      * Processes container events occurring on this container by
2265      * dispatching them to any registered ContainerListener objects.
2266      * NOTE: This method will not be called unless container events
2267      * are enabled for this component; this happens when one of the
2268      * following occurs:
2269      * <ul>
2270      * <li>A ContainerListener object is registered via
2271      *     {@code addContainerListener}
2272      * <li>Container events are enabled via {@code enableEvents}
2273      * </ul>
2274      * <p>Note that if the event parameter is {@code null}
2275      * the behavior is unspecified and may result in an
2276      * exception.
2277      *
2278      * @param e the container event
2279      * @see Component#enableEvents
2280      */
2281     protected void processContainerEvent(ContainerEvent e) {
2282         ContainerListener listener = containerListener;
2283         if (listener != null) {
2284             switch(e.getID()) {
2285               case ContainerEvent.COMPONENT_ADDED:
2286                 listener.componentAdded(e);
2287                 break;
2288               case ContainerEvent.COMPONENT_REMOVED:
2289                 listener.componentRemoved(e);
2290                 break;
2291             }
2292         }
2293     }
2294 
2295     /*
2296      * Dispatches an event to this component or one of its sub components.
2297      * Create ANCESTOR_RESIZED and ANCESTOR_MOVED events in response to
2298      * COMPONENT_RESIZED and COMPONENT_MOVED events. We have to do this
2299      * here instead of in processComponentEvent because ComponentEvents
2300      * may not be enabled for this Container.
2301      * @param e the event
2302      */
2303     void dispatchEventImpl(AWTEvent e) {
2304         if ((dispatcher != null) && dispatcher.dispatchEvent(e)) {
2305             // event was sent to a lightweight component.  The
2306             // native-produced event sent to the native container
2307             // must be properly disposed of by the peer, so it
2308             // gets forwarded.  If the native host has been removed
2309             // as a result of the sending the lightweight event,
2310             // the peer reference will be null.
2311             e.consume();
2312             if (peer != null) {
2313                 peer.handleEvent(e);
2314             }
2315             return;
2316         }
2317 
2318         super.dispatchEventImpl(e);
2319 
2320         synchronized (getTreeLock()) {
2321             switch (e.getID()) {
2322               case ComponentEvent.COMPONENT_RESIZED:
2323                 createChildHierarchyEvents(HierarchyEvent.ANCESTOR_RESIZED, 0,
2324                                            Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
2325                 break;
2326               case ComponentEvent.COMPONENT_MOVED:
2327                 createChildHierarchyEvents(HierarchyEvent.ANCESTOR_MOVED, 0,
2328                                        Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
2329                 break;
2330               default:
2331                 break;
2332             }
2333         }
2334     }
2335 
2336     /*
2337      * Dispatches an event to this component, without trying to forward
2338      * it to any subcomponents
2339      * @param e the event
2340      */
2341     void dispatchEventToSelf(AWTEvent e) {
2342         super.dispatchEventImpl(e);
2343     }
2344 
2345     /**
2346      * Fetches the top-most (deepest) lightweight component that is interested
2347      * in receiving mouse events.
2348      */
2349     Component getMouseEventTarget(int x, int y, boolean includeSelf) {
2350         return getMouseEventTarget(x, y, includeSelf,
2351                                    MouseEventTargetFilter.FILTER,
2352                                    !SEARCH_HEAVYWEIGHTS);
2353     }
2354 
2355     /**
2356      * Fetches the top-most (deepest) component to receive SunDropTargetEvents.
2357      */
2358     Component getDropTargetEventTarget(int x, int y, boolean includeSelf) {
2359         return getMouseEventTarget(x, y, includeSelf,
2360                                    DropTargetEventTargetFilter.FILTER,
2361                                    SEARCH_HEAVYWEIGHTS);
2362     }
2363 
2364     /**
2365      * A private version of getMouseEventTarget which has two additional
2366      * controllable behaviors. This method searches for the top-most
2367      * descendant of this container that contains the given coordinates
2368      * and is accepted by the given filter. The search will be constrained to
2369      * lightweight descendants if the last argument is {@code false}.
2370      *
2371      * @param filter EventTargetFilter instance to determine whether the
2372      *        given component is a valid target for this event.
2373      * @param searchHeavyweights if {@code false}, the method
2374      *        will bypass heavyweight components during the search.
2375      */
2376     private Component getMouseEventTarget(int x, int y, boolean includeSelf,
2377                                           EventTargetFilter filter,
2378                                           boolean searchHeavyweights) {
2379         Component comp = null;
2380         if (searchHeavyweights) {
2381             comp = getMouseEventTargetImpl(x, y, includeSelf, filter,
2382                                            SEARCH_HEAVYWEIGHTS,
2383                                            searchHeavyweights);
2384         }
2385 
2386         if (comp == null || comp == this) {
2387             comp = getMouseEventTargetImpl(x, y, includeSelf, filter,
2388                                            !SEARCH_HEAVYWEIGHTS,
2389                                            searchHeavyweights);
2390         }
2391 
2392         return comp;
2393     }
2394 
2395     /**
2396      * A private version of getMouseEventTarget which has three additional
2397      * controllable behaviors. This method searches for the top-most
2398      * descendant of this container that contains the given coordinates
2399      * and is accepted by the given filter. The search will be constrained to
2400      * descendants of only lightweight children or only heavyweight children
2401      * of this container depending on searchHeavyweightChildren. The search will
2402      * be constrained to only lightweight descendants of the searched children
2403      * of this container if searchHeavyweightDescendants is {@code false}.
2404      *
2405      * @param filter EventTargetFilter instance to determine whether the
2406      *        selected component is a valid target for this event.
2407      * @param searchHeavyweightChildren if {@code true}, the method
2408      *        will bypass immediate lightweight children during the search.
2409      *        If {@code false}, the methods will bypass immediate
2410      *        heavyweight children during the search.
2411      * @param searchHeavyweightDescendants if {@code false}, the method
2412      *        will bypass heavyweight descendants which are not immediate
2413      *        children during the search. If {@code true}, the method
2414      *        will traverse both lightweight and heavyweight descendants during
2415      *        the search.
2416      */
2417     private Component getMouseEventTargetImpl(int x, int y, boolean includeSelf,
2418                                          EventTargetFilter filter,
2419                                          boolean searchHeavyweightChildren,
2420                                          boolean searchHeavyweightDescendants) {
2421         synchronized (getTreeLock()) {
2422 
2423             for (int i = 0; i < component.size(); i++) {
2424                 Component comp = component.get(i);
2425                 if (comp != null && comp.visible &&
2426                     ((!searchHeavyweightChildren &&
2427                       comp.peer instanceof LightweightPeer) ||
2428                      (searchHeavyweightChildren &&
2429                       !(comp.peer instanceof LightweightPeer))) &&
2430                     comp.contains(x - comp.x, y - comp.y)) {
2431 
2432                     // found a component that intersects the point, see if there
2433                     // is a deeper possibility.
2434                     if (comp instanceof Container) {
2435                         Container child = (Container) comp;
2436                         Component deeper = child.getMouseEventTarget(
2437                                 x - child.x,
2438                                 y - child.y,
2439                                 includeSelf,
2440                                 filter,
2441                                 searchHeavyweightDescendants);
2442                         if (deeper != null) {
2443                             return deeper;
2444                         }
2445                     } else {
2446                         if (filter.accept(comp)) {
2447                             // there isn't a deeper target, but this component
2448                             // is a target
2449                             return comp;
2450                         }
2451                     }
2452                 }
2453             }
2454 
2455             boolean isPeerOK;
2456             boolean isMouseOverMe;
2457 
2458             isPeerOK = (peer instanceof LightweightPeer) || includeSelf;
2459             isMouseOverMe = contains(x,y);
2460 
2461             // didn't find a child target, return this component if it's
2462             // a possible target
2463             if (isMouseOverMe && isPeerOK && filter.accept(this)) {
2464                 return this;
2465             }
2466             // no possible target
2467             return null;
2468         }
2469     }
2470 
2471     static interface EventTargetFilter {
2472         boolean accept(final Component comp);
2473     }
2474 
2475     static class MouseEventTargetFilter implements EventTargetFilter {
2476         static final EventTargetFilter FILTER = new MouseEventTargetFilter();
2477 
2478         private MouseEventTargetFilter() {}
2479 
2480         public boolean accept(final Component comp) {
2481             return (comp.eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0
2482                 || (comp.eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0
2483                 || (comp.eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0
2484                 || comp.mouseListener != null
2485                 || comp.mouseMotionListener != null
2486                 || comp.mouseWheelListener != null;
2487         }
2488     }
2489 
2490     static class DropTargetEventTargetFilter implements EventTargetFilter {
2491         static final EventTargetFilter FILTER = new DropTargetEventTargetFilter();
2492 
2493         private DropTargetEventTargetFilter() {}
2494 
2495         public boolean accept(final Component comp) {
2496             DropTarget dt = comp.getDropTarget();
2497             return dt != null && dt.isActive();
2498         }
2499     }
2500 
2501     /**
2502      * This is called by lightweight components that want the containing
2503      * windowed parent to enable some kind of events on their behalf.
2504      * This is needed for events that are normally only dispatched to
2505      * windows to be accepted so that they can be forwarded downward to
2506      * the lightweight component that has enabled them.
2507      */
2508     void proxyEnableEvents(long events) {
2509         if (peer instanceof LightweightPeer) {
2510             // this container is lightweight.... continue sending it
2511             // upward.
2512             if (parent != null) {
2513                 parent.proxyEnableEvents(events);
2514             }
2515         } else {
2516             // This is a native container, so it needs to host
2517             // one of it's children.  If this function is called before
2518             // a peer has been created we don't yet have a dispatcher
2519             // because it has not yet been determined if this instance
2520             // is lightweight.
2521             if (dispatcher != null) {
2522                 dispatcher.enableEvents(events);
2523             }
2524         }
2525     }
2526 
2527     /**
2528      * @deprecated As of JDK version 1.1,
2529      * replaced by {@code dispatchEvent(AWTEvent e)}
2530      */
2531     @Deprecated
2532     public void deliverEvent(Event e) {
2533         Component comp = getComponentAt(e.x, e.y);
2534         if ((comp != null) && (comp != this)) {
2535             e.translate(-comp.x, -comp.y);
2536             comp.deliverEvent(e);
2537         } else {
2538             postEvent(e);
2539         }
2540     }
2541 
2542     /**
2543      * Locates the component that contains the x,y position.  The
2544      * top-most child component is returned in the case where there
2545      * is overlap in the components.  This is determined by finding
2546      * the component closest to the index 0 that claims to contain
2547      * the given point via Component.contains(), except that Components
2548      * which have native peers take precedence over those which do not
2549      * (i.e., lightweight Components).
2550      *
2551      * @param x the <i>x</i> coordinate
2552      * @param y the <i>y</i> coordinate
2553      * @return null if the component does not contain the position.
2554      * If there is no child component at the requested point and the
2555      * point is within the bounds of the container the container itself
2556      * is returned; otherwise the top-most child is returned.
2557      * @see Component#contains
2558      * @since 1.1
2559      */
2560     public Component getComponentAt(int x, int y) {
2561         return locate(x, y);
2562     }
2563 
2564     /**
2565      * @deprecated As of JDK version 1.1,
2566      * replaced by {@code getComponentAt(int, int)}.
2567      */
2568     @Deprecated
2569     public Component locate(int x, int y) {
2570         if (!contains(x, y)) {
2571             return null;
2572         }
2573         Component lightweight = null;
2574         synchronized (getTreeLock()) {
2575             // Optimized version of two passes:
2576             // see comment in sun.awt.SunGraphicsCallback
2577             for (final Component comp : component) {
2578                 if (comp.contains(x - comp.x, y - comp.y)) {
2579                     if (!comp.isLightweight()) {
2580                         // return heavyweight component as soon as possible
2581                         return comp;
2582                     }
2583                     if (lightweight == null) {
2584                         // save and return later the first lightweight component
2585                         lightweight = comp;
2586                     }
2587                 }
2588             }
2589         }
2590         return lightweight != null ? lightweight : this;
2591     }
2592 
2593     /**
2594      * Gets the component that contains the specified point.
2595      * @param      p   the point.
2596      * @return     returns the component that contains the point,
2597      *                 or {@code null} if the component does
2598      *                 not contain the point.
2599      * @see        Component#contains
2600      * @since      1.1
2601      */
2602     public Component getComponentAt(Point p) {
2603         return getComponentAt(p.x, p.y);
2604     }
2605 
2606     /**
2607      * Returns the position of the mouse pointer in this {@code Container}'s
2608      * coordinate space if the {@code Container} is under the mouse pointer,
2609      * otherwise returns {@code null}.
2610      * This method is similar to {@link Component#getMousePosition()} with the exception
2611      * that it can take the {@code Container}'s children into account.
2612      * If {@code allowChildren} is {@code false}, this method will return
2613      * a non-null value only if the mouse pointer is above the {@code Container}
2614      * directly, not above the part obscured by children.
2615      * If {@code allowChildren} is {@code true}, this method returns
2616      * a non-null value if the mouse pointer is above {@code Container} or any
2617      * of its descendants.
2618      *
2619      * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true
2620      * @param     allowChildren true if children should be taken into account
2621      * @see       Component#getMousePosition
2622      * @return    mouse coordinates relative to this {@code Component}, or null
2623      * @since     1.5
2624      */
2625     public Point getMousePosition(boolean allowChildren) throws HeadlessException {
2626         if (GraphicsEnvironment.isHeadless()) {
2627             throw new HeadlessException();
2628         }
2629         PointerInfo pi = java.security.AccessController.doPrivileged(
2630             new java.security.PrivilegedAction<PointerInfo>() {
2631                 public PointerInfo run() {
2632                     return MouseInfo.getPointerInfo();
2633                 }
2634             }
2635         );
2636         synchronized (getTreeLock()) {
2637             Component inTheSameWindow = findUnderMouseInWindow(pi);
2638             if (isSameOrAncestorOf(inTheSameWindow, allowChildren)) {
2639                 return  pointRelativeToComponent(pi.getLocation());
2640             }
2641             return null;
2642         }
2643     }
2644 
2645     boolean isSameOrAncestorOf(Component comp, boolean allowChildren) {
2646         return this == comp || (allowChildren && isParentOf(comp));
2647     }
2648 
2649     /**
2650      * Locates the visible child component that contains the specified
2651      * position.  The top-most child component is returned in the case
2652      * where there is overlap in the components.  If the containing child
2653      * component is a Container, this method will continue searching for
2654      * the deepest nested child component.  Components which are not
2655      * visible are ignored during the search.<p>
2656      *
2657      * The findComponentAt method is different from getComponentAt in
2658      * that getComponentAt only searches the Container's immediate
2659      * children; if the containing component is a Container,
2660      * findComponentAt will search that child to find a nested component.
2661      *
2662      * @param x the <i>x</i> coordinate
2663      * @param y the <i>y</i> coordinate
2664      * @return null if the component does not contain the position.
2665      * If there is no child component at the requested point and the
2666      * point is within the bounds of the container the container itself
2667      * is returned.
2668      * @see Component#contains
2669      * @see #getComponentAt
2670      * @since 1.2
2671      */
2672     public Component findComponentAt(int x, int y) {
2673         return findComponentAt(x, y, true);
2674     }
2675 
2676     /**
2677      * Private version of findComponentAt which has a controllable
2678      * behavior. Setting 'ignoreEnabled' to 'false' bypasses disabled
2679      * Components during the search. This behavior is used by the
2680      * lightweight cursor support in sun.awt.GlobalCursorManager.
2681      *
2682      * The addition of this feature is temporary, pending the
2683      * adoption of new, public API which exports this feature.
2684      */
2685     final Component findComponentAt(int x, int y, boolean ignoreEnabled) {
2686         synchronized (getTreeLock()) {
2687             if (isRecursivelyVisible()){
2688                 return findComponentAtImpl(x, y, ignoreEnabled);
2689             }
2690         }
2691         return null;
2692     }
2693 
2694     final Component findComponentAtImpl(int x, int y, boolean ignoreEnabled) {
2695         // checkTreeLock(); commented for a performance reason
2696 
2697         if (!(contains(x, y) && visible && (ignoreEnabled || enabled))) {
2698             return null;
2699         }
2700         Component lightweight = null;
2701         // Optimized version of two passes:
2702         // see comment in sun.awt.SunGraphicsCallback
2703         for (final Component comp : component) {
2704             final int x1 = x - comp.x;
2705             final int y1 = y - comp.y;
2706             if (!comp.contains(x1, y1)) {
2707                 continue; // fast path
2708             }
2709             if (!comp.isLightweight()) {
2710                 final Component child = getChildAt(comp, x1, y1, ignoreEnabled);
2711                 if (child != null) {
2712                     // return heavyweight component as soon as possible
2713                     return child;
2714                 }
2715             } else {
2716                 if (lightweight == null) {
2717                     // save and return later the first lightweight component
2718                     lightweight = getChildAt(comp, x1, y1, ignoreEnabled);
2719                 }
2720             }
2721         }
2722         return lightweight != null ? lightweight : this;
2723     }
2724 
2725     /**
2726      * Helper method for findComponentAtImpl. Finds a child component using
2727      * findComponentAtImpl for Container and getComponentAt for Component.
2728      */
2729     private static Component getChildAt(Component comp, int x, int y,
2730                                         boolean ignoreEnabled) {
2731         if (comp instanceof Container) {
2732             comp = ((Container) comp).findComponentAtImpl(x, y,
2733                                                           ignoreEnabled);
2734         } else {
2735             comp = comp.getComponentAt(x, y);
2736         }
2737         if (comp != null && comp.visible &&
2738                 (ignoreEnabled || comp.enabled)) {
2739             return comp;
2740         }
2741         return null;
2742     }
2743 
2744     /**
2745      * Locates the visible child component that contains the specified
2746      * point.  The top-most child component is returned in the case
2747      * where there is overlap in the components.  If the containing child
2748      * component is a Container, this method will continue searching for
2749      * the deepest nested child component.  Components which are not
2750      * visible are ignored during the search.<p>
2751      *
2752      * The findComponentAt method is different from getComponentAt in
2753      * that getComponentAt only searches the Container's immediate
2754      * children; if the containing component is a Container,
2755      * findComponentAt will search that child to find a nested component.
2756      *
2757      * @param      p   the point.
2758      * @return null if the component does not contain the position.
2759      * If there is no child component at the requested point and the
2760      * point is within the bounds of the container the container itself
2761      * is returned.
2762      * @throws NullPointerException if {@code p} is {@code null}
2763      * @see Component#contains
2764      * @see #getComponentAt
2765      * @since 1.2
2766      */
2767     public Component findComponentAt(Point p) {
2768         return findComponentAt(p.x, p.y);
2769     }
2770 
2771     /**
2772      * Makes this Container displayable by connecting it to
2773      * a native screen resource.  Making a container displayable will
2774      * cause all of its children to be made displayable.
2775      * This method is called internally by the toolkit and should
2776      * not be called directly by programs.
2777      * @see Component#isDisplayable
2778      * @see #removeNotify
2779      */
2780     public void addNotify() {
2781         synchronized (getTreeLock()) {
2782             // addNotify() on the children may cause proxy event enabling
2783             // on this instance, so we first call super.addNotify() and
2784             // possibly create an lightweight event dispatcher before calling
2785             // addNotify() on the children which may be lightweight.
2786             super.addNotify();
2787             if (! (peer instanceof LightweightPeer)) {
2788                 dispatcher = new LightweightDispatcher(this);
2789             }
2790 
2791             // We shouldn't use iterator because of the Swing menu
2792             // implementation specifics:
2793             // the menu is being assigned as a child to JLayeredPane
2794             // instead of particular component so always affect
2795             // collection of component if menu is becoming shown or hidden.
2796             for (int i = 0; i < component.size(); i++) {
2797                 component.get(i).addNotify();
2798             }
2799         }
2800     }
2801 
2802     /**
2803      * Makes this Container undisplayable by removing its connection
2804      * to its native screen resource.  Making a container undisplayable
2805      * will cause all of its children to be made undisplayable.
2806      * This method is called by the toolkit internally and should
2807      * not be called directly by programs.
2808      * @see Component#isDisplayable
2809      * @see #addNotify
2810      */
2811     public void removeNotify() {
2812         synchronized (getTreeLock()) {
2813             // We shouldn't use iterator because of the Swing menu
2814             // implementation specifics:
2815             // the menu is being assigned as a child to JLayeredPane
2816             // instead of particular component so always affect
2817             // collection of component if menu is becoming shown or hidden.
2818             for (int i = component.size()-1 ; i >= 0 ; i--) {
2819                 Component comp = component.get(i);
2820                 if (comp != null) {
2821                     // Fix for 6607170.
2822                     // We want to suppress focus change on disposal
2823                     // of the focused component. But because of focus
2824                     // is asynchronous, we should suppress focus change
2825                     // on every component in case it receives native focus
2826                     // in the process of disposal.
2827                     comp.setAutoFocusTransferOnDisposal(false);
2828                     comp.removeNotify();
2829                     comp.setAutoFocusTransferOnDisposal(true);
2830                  }
2831              }
2832             // If some of the children had focus before disposal then it still has.
2833             // Auto-transfer focus to the next (or previous) component if auto-transfer
2834             // is enabled.
2835             if (containsFocus() && KeyboardFocusManager.isAutoFocusTransferEnabledFor(this)) {
2836                 if (!transferFocus(false)) {
2837                     transferFocusBackward(true);
2838                 }
2839             }
2840             if ( dispatcher != null ) {
2841                 dispatcher.dispose();
2842                 dispatcher = null;
2843             }
2844             super.removeNotify();
2845         }
2846     }
2847 
2848     /**
2849      * Checks if the component is contained in the component hierarchy of
2850      * this container.
2851      * @param c the component
2852      * @return     {@code true} if it is an ancestor;
2853      *             {@code false} otherwise.
2854      * @since      1.1
2855      */
2856     public boolean isAncestorOf(Component c) {
2857         Container p;
2858         if (c == null || ((p = c.getParent()) == null)) {
2859             return false;
2860         }
2861         while (p != null) {
2862             if (p == this) {
2863                 return true;
2864             }
2865             p = p.getParent();
2866         }
2867         return false;
2868     }
2869 
2870     /*
2871      * The following code was added to support modal JInternalFrames
2872      * Unfortunately this code has to be added here so that we can get access to
2873      * some private AWT classes like SequencedEvent.
2874      *
2875      * The native container of the LW component has this field set
2876      * to tell it that it should block Mouse events for all LW
2877      * children except for the modal component.
2878      *
2879      * In the case of nested Modal components, we store the previous
2880      * modal component in the new modal components value of modalComp;
2881      */
2882 
2883     transient Component modalComp;
2884     transient AppContext modalAppContext;
2885 
2886     private void startLWModal() {
2887         // Store the app context on which this component is being shown.
2888         // Event dispatch thread of this app context will be sleeping until
2889         // we wake it by any event from hideAndDisposeHandler().
2890         modalAppContext = AppContext.getAppContext();
2891 
2892         // keep the KeyEvents from being dispatched
2893         // until the focus has been transferred
2894         long time = Toolkit.getEventQueue().getMostRecentKeyEventTime();
2895         Component predictedFocusOwner = (Component.isInstanceOf(this, "javax.swing.JInternalFrame")) ? ((javax.swing.JInternalFrame)(this)).getMostRecentFocusOwner() : null;
2896         if (predictedFocusOwner != null) {
2897             KeyboardFocusManager.getCurrentKeyboardFocusManager().
2898                 enqueueKeyEvents(time, predictedFocusOwner);
2899         }
2900         // We have two mechanisms for blocking: 1. If we're on the
2901         // EventDispatchThread, start a new event pump. 2. If we're
2902         // on any other thread, call wait() on the treelock.
2903         final Container nativeContainer;
2904         synchronized (getTreeLock()) {
2905             nativeContainer = getHeavyweightContainer();
2906             if (nativeContainer.modalComp != null) {
2907                 this.modalComp =  nativeContainer.modalComp;
2908                 nativeContainer.modalComp = this;
2909                 return;
2910             }
2911             else {
2912                 nativeContainer.modalComp = this;
2913             }
2914         }
2915 
2916         Runnable pumpEventsForHierarchy = () -> {
2917             EventDispatchThread dispatchThread = (EventDispatchThread)Thread.currentThread();
2918             dispatchThread.pumpEventsForHierarchy(() -> nativeContainer.modalComp != null,
2919                     Container.this);
2920         };
2921 
2922         if (EventQueue.isDispatchThread()) {
2923             SequencedEvent currentSequencedEvent =
2924                 KeyboardFocusManager.getCurrentKeyboardFocusManager().
2925                 getCurrentSequencedEvent();
2926             if (currentSequencedEvent != null) {
2927                 currentSequencedEvent.dispose();
2928             }
2929 
2930             pumpEventsForHierarchy.run();
2931         } else {
2932             synchronized (getTreeLock()) {
2933                 Toolkit.getEventQueue().
2934                     postEvent(new PeerEvent(this,
2935                                 pumpEventsForHierarchy,
2936                                 PeerEvent.PRIORITY_EVENT));
2937                 while (nativeContainer.modalComp != null)
2938                 {
2939                     try {
2940                         getTreeLock().wait();
2941                     } catch (InterruptedException e) {
2942                         break;
2943                     }
2944                 }
2945             }
2946         }
2947         if (predictedFocusOwner != null) {
2948             KeyboardFocusManager.getCurrentKeyboardFocusManager().
2949                 dequeueKeyEvents(time, predictedFocusOwner);
2950         }
2951     }
2952 
2953     private void stopLWModal() {
2954         synchronized (getTreeLock()) {
2955             if (modalAppContext != null) {
2956                 Container nativeContainer = getHeavyweightContainer();
2957                 if(nativeContainer != null) {
2958                     if (this.modalComp !=  null) {
2959                         nativeContainer.modalComp = this.modalComp;
2960                         this.modalComp = null;
2961                         return;
2962                     }
2963                     else {
2964                         nativeContainer.modalComp = null;
2965                     }
2966                 }
2967                 // Wake up event dispatch thread on which the dialog was
2968                 // initially shown
2969                 SunToolkit.postEvent(modalAppContext,
2970                         new PeerEvent(this,
2971                                 new WakingRunnable(),
2972                                 PeerEvent.PRIORITY_EVENT));
2973             }
2974             EventQueue.invokeLater(new WakingRunnable());
2975             getTreeLock().notifyAll();
2976         }
2977     }
2978 
2979     static final class WakingRunnable implements Runnable {
2980         public void run() {
2981         }
2982     }
2983 
2984     /* End of JOptionPane support code */
2985 
2986     /**
2987      * Returns a string representing the state of this {@code Container}.
2988      * This method is intended to be used only for debugging purposes, and the
2989      * content and format of the returned string may vary between
2990      * implementations. The returned string may be empty but may not be
2991      * {@code null}.
2992      *
2993      * @return    the parameter string of this container
2994      */
2995     protected String paramString() {
2996         String str = super.paramString();
2997         LayoutManager layoutMgr = this.layoutMgr;
2998         if (layoutMgr != null) {
2999             str += ",layout=" + layoutMgr.getClass().getName();
3000         }
3001         return str;
3002     }
3003 
3004     /**
3005      * Prints a listing of this container to the specified output
3006      * stream. The listing starts at the specified indentation.
3007      * <p>
3008      * The immediate children of the container are printed with
3009      * an indentation of {@code indent+1}.  The children
3010      * of those children are printed at {@code indent+2}
3011      * and so on.
3012      *
3013      * @param    out      a print stream
3014      * @param    indent   the number of spaces to indent
3015      * @throws   NullPointerException if {@code out} is {@code null}
3016      * @see      Component#list(java.io.PrintStream, int)
3017      * @since    1.0
3018      */
3019     public void list(PrintStream out, int indent) {
3020         super.list(out, indent);
3021         synchronized(getTreeLock()) {
3022             for (int i = 0; i < component.size(); i++) {
3023                 Component comp = component.get(i);
3024                 if (comp != null) {
3025                     comp.list(out, indent+1);
3026                 }
3027             }
3028         }
3029     }
3030 
3031     /**
3032      * Prints out a list, starting at the specified indentation,
3033      * to the specified print writer.
3034      * <p>
3035      * The immediate children of the container are printed with
3036      * an indentation of {@code indent+1}.  The children
3037      * of those children are printed at {@code indent+2}
3038      * and so on.
3039      *
3040      * @param    out      a print writer
3041      * @param    indent   the number of spaces to indent
3042      * @throws   NullPointerException if {@code out} is {@code null}
3043      * @see      Component#list(java.io.PrintWriter, int)
3044      * @since    1.1
3045      */
3046     public void list(PrintWriter out, int indent) {
3047         super.list(out, indent);
3048         synchronized(getTreeLock()) {
3049             for (int i = 0; i < component.size(); i++) {
3050                 Component comp = component.get(i);
3051                 if (comp != null) {
3052                     comp.list(out, indent+1);
3053                 }
3054             }
3055         }
3056     }
3057 
3058     /**
3059      * Sets the focus traversal keys for a given traversal operation for this
3060      * Container.
3061      * <p>
3062      * The default values for a Container's focus traversal keys are
3063      * implementation-dependent. Sun recommends that all implementations for a
3064      * particular native platform use the same default values. The
3065      * recommendations for Windows and Unix are listed below. These
3066      * recommendations are used in the Sun AWT implementations.
3067      *
3068      * <table class="striped">
3069      * <caption>Recommended default values for a Container's focus traversal
3070      * keys</caption>
3071      * <thead>
3072      *   <tr>
3073      *     <th scope="col">Identifier
3074      *     <th scope="col">Meaning
3075      *     <th scope="col">Default
3076      * </thead>
3077      * <tbody>
3078      *   <tr>
3079      *     <th scope="row">KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS
3080      *     <td>Normal forward keyboard traversal
3081      *     <td>TAB on KEY_PRESSED, CTRL-TAB on KEY_PRESSED
3082      *   <tr>
3083      *     <th scope="row">KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS
3084      *     <td>Normal reverse keyboard traversal
3085      *     <td>SHIFT-TAB on KEY_PRESSED, CTRL-SHIFT-TAB on KEY_PRESSED
3086      *   <tr>
3087      *     <th scope="row">KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
3088      *     <td>Go up one focus traversal cycle
3089      *     <td>none
3090      *   <tr>
3091      *     <th scope="row">KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
3092      *     <td>Go down one focus traversal cycle
3093      *     <td>none
3094      * </tbody>
3095      * </table>
3096      *
3097      * To disable a traversal key, use an empty Set; Collections.EMPTY_SET is
3098      * recommended.
3099      * <p>
3100      * Using the AWTKeyStroke API, client code can specify on which of two
3101      * specific KeyEvents, KEY_PRESSED or KEY_RELEASED, the focus traversal
3102      * operation will occur. Regardless of which KeyEvent is specified,
3103      * however, all KeyEvents related to the focus traversal key, including the
3104      * associated KEY_TYPED event, will be consumed, and will not be dispatched
3105      * to any Container. It is a runtime error to specify a KEY_TYPED event as
3106      * mapping to a focus traversal operation, or to map the same event to
3107      * multiple default focus traversal operations.
3108      * <p>
3109      * If a value of null is specified for the Set, this Container inherits the
3110      * Set from its parent. If all ancestors of this Container have null
3111      * specified for the Set, then the current KeyboardFocusManager's default
3112      * Set is used.
3113      * <p>
3114      * This method may throw a {@code ClassCastException} if any {@code Object}
3115      * in {@code keystrokes} is not an {@code AWTKeyStroke}.
3116      *
3117      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
3118      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
3119      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
3120      *        KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
3121      * @param keystrokes the Set of AWTKeyStroke for the specified operation
3122      * @see #getFocusTraversalKeys
3123      * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
3124      * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
3125      * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
3126      * @see KeyboardFocusManager#DOWN_CYCLE_TRAVERSAL_KEYS
3127      * @throws IllegalArgumentException if id is not one of
3128      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
3129      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
3130      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
3131      *         KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS, or if keystrokes
3132      *         contains null, or if any keystroke represents a KEY_TYPED event,
3133      *         or if any keystroke already maps to another focus traversal
3134      *         operation for this Container
3135      * @since 1.4
3136      */
3137     public void setFocusTraversalKeys(int id,
3138                                       Set<? extends AWTKeyStroke> keystrokes)
3139     {
3140         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH) {
3141             throw new IllegalArgumentException("invalid focus traversal key identifier");
3142         }
3143 
3144         // Don't call super.setFocusTraversalKey. The Component parameter check
3145         // does not allow DOWN_CYCLE_TRAVERSAL_KEYS, but we do.
3146         setFocusTraversalKeys_NoIDCheck(id, keystrokes);
3147     }
3148 
3149     /**
3150      * Returns the Set of focus traversal keys for a given traversal operation
3151      * for this Container. (See
3152      * {@code setFocusTraversalKeys} for a full description of each key.)
3153      * <p>
3154      * If a Set of traversal keys has not been explicitly defined for this
3155      * Container, then this Container's parent's Set is returned. If no Set
3156      * has been explicitly defined for any of this Container's ancestors, then
3157      * the current KeyboardFocusManager's default Set is returned.
3158      *
3159      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
3160      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
3161      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
3162      *        KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
3163      * @return the Set of AWTKeyStrokes for the specified operation. The Set
3164      *         will be unmodifiable, and may be empty. null will never be
3165      *         returned.
3166      * @see #setFocusTraversalKeys
3167      * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
3168      * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
3169      * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
3170      * @see KeyboardFocusManager#DOWN_CYCLE_TRAVERSAL_KEYS
3171      * @throws IllegalArgumentException if id is not one of
3172      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
3173      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
3174      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
3175      *         KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
3176      * @since 1.4
3177      */
3178     public Set<AWTKeyStroke> getFocusTraversalKeys(int id) {
3179         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH) {
3180             throw new IllegalArgumentException("invalid focus traversal key identifier");
3181         }
3182 
3183         // Don't call super.getFocusTraversalKey. The Component parameter check
3184         // does not allow DOWN_CYCLE_TRAVERSAL_KEY, but we do.
3185         return getFocusTraversalKeys_NoIDCheck(id);
3186     }
3187 
3188     /**
3189      * Returns whether the Set of focus traversal keys for the given focus
3190      * traversal operation has been explicitly defined for this Container. If
3191      * this method returns {@code false}, this Container is inheriting the
3192      * Set from an ancestor, or from the current KeyboardFocusManager.
3193      *
3194      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
3195      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
3196      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
3197      *        KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
3198      * @return {@code true} if the Set of focus traversal keys for the
3199      *         given focus traversal operation has been explicitly defined for
3200      *         this Component; {@code false} otherwise.
3201      * @throws IllegalArgumentException if id is not one of
3202      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
3203      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
3204      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
3205      *        KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
3206      * @since 1.4
3207      */
3208     public boolean areFocusTraversalKeysSet(int id) {
3209         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH) {
3210             throw new IllegalArgumentException("invalid focus traversal key identifier");
3211         }
3212 
3213         return (focusTraversalKeys != null && focusTraversalKeys[id] != null);
3214     }
3215 
3216     /**
3217      * Returns whether the specified Container is the focus cycle root of this
3218      * Container's focus traversal cycle. Each focus traversal cycle has only
3219      * a single focus cycle root and each Container which is not a focus cycle
3220      * root belongs to only a single focus traversal cycle. Containers which
3221      * are focus cycle roots belong to two cycles: one rooted at the Container
3222      * itself, and one rooted at the Container's nearest focus-cycle-root
3223      * ancestor. This method will return {@code true} for both such
3224      * Containers in this case.
3225      *
3226      * @param container the Container to be tested
3227      * @return {@code true} if the specified Container is a focus-cycle-
3228      *         root of this Container; {@code false} otherwise
3229      * @see #isFocusCycleRoot()
3230      * @since 1.4
3231      */
3232     public boolean isFocusCycleRoot(Container container) {
3233         if (isFocusCycleRoot() && container == this) {
3234             return true;
3235         } else {
3236             return super.isFocusCycleRoot(container);
3237         }
3238     }
3239 
3240     private Container findTraversalRoot() {
3241         // I potentially have two roots, myself and my root parent
3242         // If I am the current root, then use me
3243         // If none of my parents are roots, then use me
3244         // If my root parent is the current root, then use my root parent
3245         // If neither I nor my root parent is the current root, then
3246         // use my root parent (a guess)
3247 
3248         Container currentFocusCycleRoot = KeyboardFocusManager.
3249             getCurrentKeyboardFocusManager().getCurrentFocusCycleRoot();
3250         Container root;
3251 
3252         if (currentFocusCycleRoot == this) {
3253             root = this;
3254         } else {
3255             root = getFocusCycleRootAncestor();
3256             if (root == null) {
3257                 root = this;
3258             }
3259         }
3260 
3261         if (root != currentFocusCycleRoot) {
3262             KeyboardFocusManager.getCurrentKeyboardFocusManager().
3263                 setGlobalCurrentFocusCycleRootPriv(root);
3264         }
3265         return root;
3266     }
3267 
3268     final boolean containsFocus() {
3269         final Component focusOwner = KeyboardFocusManager.
3270             getCurrentKeyboardFocusManager().getFocusOwner();
3271         return isParentOf(focusOwner);
3272     }
3273 
3274     /**
3275      * Check if this component is the child of this container or its children.
3276      * Note: this function acquires treeLock
3277      * Note: this function traverses children tree only in one Window.
3278      * @param comp a component in test, must not be null
3279      */
3280     private boolean isParentOf(Component comp) {
3281         synchronized(getTreeLock()) {
3282             while (comp != null && comp != this && !(comp instanceof Window)) {
3283                 comp = comp.getParent();
3284             }
3285             return (comp == this);
3286         }
3287     }
3288 
3289     void clearMostRecentFocusOwnerOnHide() {
3290         boolean reset = false;
3291         Window window = null;
3292 
3293         synchronized (getTreeLock()) {
3294             window = getContainingWindow();
3295             if (window != null) {
3296                 Component comp = KeyboardFocusManager.getMostRecentFocusOwner(window);
3297                 reset = ((comp == this) || isParentOf(comp));
3298                 // This synchronized should always be the second in a pair
3299                 // (tree lock, KeyboardFocusManager.class)
3300                 synchronized(KeyboardFocusManager.class) {
3301                     Component storedComp = window.getTemporaryLostComponent();
3302                     if (isParentOf(storedComp) || storedComp == this) {
3303                         window.setTemporaryLostComponent(null);
3304                     }
3305                 }
3306             }
3307         }
3308 
3309         if (reset) {
3310             KeyboardFocusManager.setMostRecentFocusOwner(window, null);
3311         }
3312     }
3313 
3314     void clearCurrentFocusCycleRootOnHide() {
3315         KeyboardFocusManager kfm =
3316             KeyboardFocusManager.getCurrentKeyboardFocusManager();
3317         Container cont = kfm.getCurrentFocusCycleRoot();
3318 
3319         if (cont == this || isParentOf(cont)) {
3320             kfm.setGlobalCurrentFocusCycleRootPriv(null);
3321         }
3322     }
3323 
3324     final Container getTraversalRoot() {
3325         if (isFocusCycleRoot()) {
3326             return findTraversalRoot();
3327         }
3328 
3329         return super.getTraversalRoot();
3330     }
3331 
3332     /**
3333      * Sets the focus traversal policy that will manage keyboard traversal of
3334      * this Container's children, if this Container is a focus cycle root. If
3335      * the argument is null, this Container inherits its policy from its focus-
3336      * cycle-root ancestor. If the argument is non-null, this policy will be
3337      * inherited by all focus-cycle-root children that have no keyboard-
3338      * traversal policy of their own (as will, recursively, their focus-cycle-
3339      * root children).
3340      * <p>
3341      * If this Container is not a focus cycle root, the policy will be
3342      * remembered, but will not be used or inherited by this or any other
3343      * Containers until this Container is made a focus cycle root.
3344      *
3345      * @param policy the new focus traversal policy for this Container
3346      * @see #getFocusTraversalPolicy
3347      * @see #setFocusCycleRoot
3348      * @see #isFocusCycleRoot
3349      * @since 1.4
3350      */
3351     public void setFocusTraversalPolicy(FocusTraversalPolicy policy) {
3352         FocusTraversalPolicy oldPolicy;
3353         synchronized (this) {
3354             oldPolicy = this.focusTraversalPolicy;
3355             this.focusTraversalPolicy = policy;
3356         }
3357         firePropertyChange("focusTraversalPolicy", oldPolicy, policy);
3358     }
3359 
3360     /**
3361      * Returns the focus traversal policy that will manage keyboard traversal
3362      * of this Container's children, or null if this Container is not a focus
3363      * cycle root. If no traversal policy has been explicitly set for this
3364      * Container, then this Container's focus-cycle-root ancestor's policy is
3365      * returned.
3366      *
3367      * @return this Container's focus traversal policy, or null if this
3368      *         Container is not a focus cycle root.
3369      * @see #setFocusTraversalPolicy
3370      * @see #setFocusCycleRoot
3371      * @see #isFocusCycleRoot
3372      * @since 1.4
3373      */
3374     public FocusTraversalPolicy getFocusTraversalPolicy() {
3375         if (!isFocusTraversalPolicyProvider() && !isFocusCycleRoot()) {
3376             return null;
3377         }
3378 
3379         FocusTraversalPolicy policy = this.focusTraversalPolicy;
3380         if (policy != null) {
3381             return policy;
3382         }
3383 
3384         Container rootAncestor = getFocusCycleRootAncestor();
3385         if (rootAncestor != null) {
3386             return rootAncestor.getFocusTraversalPolicy();
3387         } else {
3388             return KeyboardFocusManager.getCurrentKeyboardFocusManager().
3389                 getDefaultFocusTraversalPolicy();
3390         }
3391     }
3392 
3393     /**
3394      * Returns whether the focus traversal policy has been explicitly set for
3395      * this Container. If this method returns {@code false}, this
3396      * Container will inherit its focus traversal policy from an ancestor.
3397      *
3398      * @return {@code true} if the focus traversal policy has been
3399      *         explicitly set for this Container; {@code false} otherwise.
3400      * @since 1.4
3401      */
3402     public boolean isFocusTraversalPolicySet() {
3403         return (focusTraversalPolicy != null);
3404     }
3405 
3406     /**
3407      * Sets whether this Container is the root of a focus traversal cycle. Once
3408      * focus enters a traversal cycle, typically it cannot leave it via focus
3409      * traversal unless one of the up- or down-cycle keys is pressed. Normal
3410      * traversal is limited to this Container, and all of this Container's
3411      * descendants that are not descendants of inferior focus cycle roots. Note
3412      * that a FocusTraversalPolicy may bend these restrictions, however. For
3413      * example, ContainerOrderFocusTraversalPolicy supports implicit down-cycle
3414      * traversal.
3415      * <p>
3416      * The alternative way to specify the traversal order of this Container's
3417      * children is to make this Container a
3418      * <a href="doc-files/FocusSpec.html#FocusTraversalPolicyProviders">focus traversal policy provider</a>.
3419      *
3420      * @param focusCycleRoot indicates whether this Container is the root of a
3421      *        focus traversal cycle
3422      * @see #isFocusCycleRoot()
3423      * @see #setFocusTraversalPolicy
3424      * @see #getFocusTraversalPolicy
3425      * @see ContainerOrderFocusTraversalPolicy
3426      * @see #setFocusTraversalPolicyProvider
3427      * @since 1.4
3428      */
3429     public void setFocusCycleRoot(boolean focusCycleRoot) {
3430         boolean oldFocusCycleRoot;
3431         synchronized (this) {
3432             oldFocusCycleRoot = this.focusCycleRoot;
3433             this.focusCycleRoot = focusCycleRoot;
3434         }
3435         firePropertyChange("focusCycleRoot", oldFocusCycleRoot,
3436                            focusCycleRoot);
3437     }
3438 
3439     /**
3440      * Returns whether this Container is the root of a focus traversal cycle.
3441      * Once focus enters a traversal cycle, typically it cannot leave it via
3442      * focus traversal unless one of the up- or down-cycle keys is pressed.
3443      * Normal traversal is limited to this Container, and all of this
3444      * Container's descendants that are not descendants of inferior focus
3445      * cycle roots. Note that a FocusTraversalPolicy may bend these
3446      * restrictions, however. For example, ContainerOrderFocusTraversalPolicy
3447      * supports implicit down-cycle traversal.
3448      *
3449      * @return whether this Container is the root of a focus traversal cycle
3450      * @see #setFocusCycleRoot
3451      * @see #setFocusTraversalPolicy
3452      * @see #getFocusTraversalPolicy
3453      * @see ContainerOrderFocusTraversalPolicy
3454      * @since 1.4
3455      */
3456     public boolean isFocusCycleRoot() {
3457         return focusCycleRoot;
3458     }
3459 
3460     /**
3461      * Sets whether this container will be used to provide focus
3462      * traversal policy. Container with this property as
3463      * {@code true} will be used to acquire focus traversal policy
3464      * instead of closest focus cycle root ancestor.
3465      * @param provider indicates whether this container will be used to
3466      *                provide focus traversal policy
3467      * @see #setFocusTraversalPolicy
3468      * @see #getFocusTraversalPolicy
3469      * @see #isFocusTraversalPolicyProvider
3470      * @since 1.5
3471      */
3472     public final void setFocusTraversalPolicyProvider(boolean provider) {
3473         boolean oldProvider;
3474         synchronized(this) {
3475             oldProvider = focusTraversalPolicyProvider;
3476             focusTraversalPolicyProvider = provider;
3477         }
3478         firePropertyChange("focusTraversalPolicyProvider", oldProvider, provider);
3479     }
3480 
3481     /**
3482      * Returns whether this container provides focus traversal
3483      * policy. If this property is set to {@code true} then when
3484      * keyboard focus manager searches container hierarchy for focus
3485      * traversal policy and encounters this container before any other
3486      * container with this property as true or focus cycle roots then
3487      * its focus traversal policy will be used instead of focus cycle
3488      * root's policy.
3489      * @see #setFocusTraversalPolicy
3490      * @see #getFocusTraversalPolicy
3491      * @see #setFocusCycleRoot
3492      * @see #setFocusTraversalPolicyProvider
3493      * @return {@code true} if this container provides focus traversal
3494      *         policy, {@code false} otherwise
3495      * @since 1.5
3496      */
3497     public final boolean isFocusTraversalPolicyProvider() {
3498         return focusTraversalPolicyProvider;
3499     }
3500 
3501     /**
3502      * Transfers the focus down one focus traversal cycle. If this Container is
3503      * a focus cycle root, then the focus owner is set to this Container's
3504      * default Component to focus, and the current focus cycle root is set to
3505      * this Container. If this Container is not a focus cycle root, then no
3506      * focus traversal operation occurs.
3507      *
3508      * @see       Component#requestFocus()
3509      * @see       #isFocusCycleRoot
3510      * @see       #setFocusCycleRoot
3511      * @since     1.4
3512      */
3513     public void transferFocusDownCycle() {
3514         if (isFocusCycleRoot()) {
3515             KeyboardFocusManager.getCurrentKeyboardFocusManager().
3516                 setGlobalCurrentFocusCycleRootPriv(this);
3517             Component toFocus = getFocusTraversalPolicy().
3518                 getDefaultComponent(this);
3519             if (toFocus != null) {
3520                 toFocus.requestFocus(FocusEvent.Cause.TRAVERSAL_DOWN);
3521             }
3522         }
3523     }
3524 
3525     void preProcessKeyEvent(KeyEvent e) {
3526         Container parent = this.parent;
3527         if (parent != null) {
3528             parent.preProcessKeyEvent(e);
3529         }
3530     }
3531 
3532     void postProcessKeyEvent(KeyEvent e) {
3533         Container parent = this.parent;
3534         if (parent != null) {
3535             parent.postProcessKeyEvent(e);
3536         }
3537     }
3538 
3539     boolean postsOldMouseEvents() {
3540         return true;
3541     }
3542 
3543     /**
3544      * Sets the {@code ComponentOrientation} property of this container
3545      * and all components contained within it.
3546      * <p>
3547      * This method changes layout-related information, and therefore,
3548      * invalidates the component hierarchy.
3549      *
3550      * @param o the new component orientation of this container and
3551      *        the components contained within it.
3552      * @exception NullPointerException if {@code orientation} is null.
3553      * @see Component#setComponentOrientation
3554      * @see Component#getComponentOrientation
3555      * @see #invalidate
3556      * @since 1.4
3557      */
3558     public void applyComponentOrientation(ComponentOrientation o) {
3559         super.applyComponentOrientation(o);
3560         synchronized (getTreeLock()) {
3561             for (int i = 0; i < component.size(); i++) {
3562                 Component comp = component.get(i);
3563                 comp.applyComponentOrientation(o);
3564             }
3565         }
3566     }
3567 
3568     /**
3569      * Adds a PropertyChangeListener to the listener list. The listener is
3570      * registered for all bound properties of this class, including the
3571      * following:
3572      * <ul>
3573      *    <li>this Container's font ("font")</li>
3574      *    <li>this Container's background color ("background")</li>
3575      *    <li>this Container's foreground color ("foreground")</li>
3576      *    <li>this Container's focusability ("focusable")</li>
3577      *    <li>this Container's focus traversal keys enabled state
3578      *        ("focusTraversalKeysEnabled")</li>
3579      *    <li>this Container's Set of FORWARD_TRAVERSAL_KEYS
3580      *        ("forwardFocusTraversalKeys")</li>
3581      *    <li>this Container's Set of BACKWARD_TRAVERSAL_KEYS
3582      *        ("backwardFocusTraversalKeys")</li>
3583      *    <li>this Container's Set of UP_CYCLE_TRAVERSAL_KEYS
3584      *        ("upCycleFocusTraversalKeys")</li>
3585      *    <li>this Container's Set of DOWN_CYCLE_TRAVERSAL_KEYS
3586      *        ("downCycleFocusTraversalKeys")</li>
3587      *    <li>this Container's focus traversal policy ("focusTraversalPolicy")
3588      *        </li>
3589      *    <li>this Container's focus-cycle-root state ("focusCycleRoot")</li>
3590      * </ul>
3591      * Note that if this Container is inheriting a bound property, then no
3592      * event will be fired in response to a change in the inherited property.
3593      * <p>
3594      * If listener is null, no exception is thrown and no action is performed.
3595      *
3596      * @param    listener  the PropertyChangeListener to be added
3597      *
3598      * @see Component#removePropertyChangeListener
3599      * @see #addPropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener)
3600      */
3601     public void addPropertyChangeListener(PropertyChangeListener listener) {
3602         super.addPropertyChangeListener(listener);
3603     }
3604 
3605     /**
3606      * Adds a PropertyChangeListener to the listener list for a specific
3607      * property. The specified property may be user-defined, or one of the
3608      * following defaults:
3609      * <ul>
3610      *    <li>this Container's font ("font")</li>
3611      *    <li>this Container's background color ("background")</li>
3612      *    <li>this Container's foreground color ("foreground")</li>
3613      *    <li>this Container's focusability ("focusable")</li>
3614      *    <li>this Container's focus traversal keys enabled state
3615      *        ("focusTraversalKeysEnabled")</li>
3616      *    <li>this Container's Set of FORWARD_TRAVERSAL_KEYS
3617      *        ("forwardFocusTraversalKeys")</li>
3618      *    <li>this Container's Set of BACKWARD_TRAVERSAL_KEYS
3619      *        ("backwardFocusTraversalKeys")</li>
3620      *    <li>this Container's Set of UP_CYCLE_TRAVERSAL_KEYS
3621      *        ("upCycleFocusTraversalKeys")</li>
3622      *    <li>this Container's Set of DOWN_CYCLE_TRAVERSAL_KEYS
3623      *        ("downCycleFocusTraversalKeys")</li>
3624      *    <li>this Container's focus traversal policy ("focusTraversalPolicy")
3625      *        </li>
3626      *    <li>this Container's focus-cycle-root state ("focusCycleRoot")</li>
3627      *    <li>this Container's focus-traversal-policy-provider state("focusTraversalPolicyProvider")</li>
3628      *    <li>this Container's focus-traversal-policy-provider state("focusTraversalPolicyProvider")</li>
3629      * </ul>
3630      * Note that if this Container is inheriting a bound property, then no
3631      * event will be fired in response to a change in the inherited property.
3632      * <p>
3633      * If listener is null, no exception is thrown and no action is performed.
3634      *
3635      * @param propertyName one of the property names listed above
3636      * @param listener the PropertyChangeListener to be added
3637      *
3638      * @see #addPropertyChangeListener(java.beans.PropertyChangeListener)
3639      * @see Component#removePropertyChangeListener
3640      */
3641     public void addPropertyChangeListener(String propertyName,
3642                                           PropertyChangeListener listener) {
3643         super.addPropertyChangeListener(propertyName, listener);
3644     }
3645 
3646     // Serialization support. A Container is responsible for restoring the
3647     // parent fields of its component children.
3648 
3649     /**
3650      * Container Serial Data Version.
3651      */
3652     private int containerSerializedDataVersion = 1;
3653 
3654     /**
3655      * Serializes this {@code Container} to the specified
3656      * {@code ObjectOutputStream}.
3657      * <ul>
3658      *    <li>Writes default serializable fields to the stream.</li>
3659      *    <li>Writes a list of serializable ContainerListener(s) as optional
3660      *        data. The non-serializable ContainerListener(s) are detected and
3661      *        no attempt is made to serialize them.</li>
3662      *    <li>Write this Container's FocusTraversalPolicy if and only if it
3663      *        is Serializable; otherwise, {@code null} is written.</li>
3664      * </ul>
3665      *
3666      * @param s the {@code ObjectOutputStream} to write
3667      * @serialData {@code null} terminated sequence of 0 or more pairs;
3668      *   the pair consists of a {@code String} and {@code Object};
3669      *   the {@code String} indicates the type of object and
3670      *   is one of the following:
3671      *   {@code containerListenerK} indicating an
3672      *     {@code ContainerListener} object;
3673      *   the {@code Container}'s {@code FocusTraversalPolicy},
3674      *     or {@code null}
3675      *
3676      * @see AWTEventMulticaster#save(java.io.ObjectOutputStream, java.lang.String, java.util.EventListener)
3677      * @see Container#containerListenerK
3678      * @see #readObject(ObjectInputStream)
3679      */
3680     private void writeObject(ObjectOutputStream s) throws IOException {
3681         ObjectOutputStream.PutField f = s.putFields();
3682         f.put("ncomponents", component.size());
3683         f.put("component", component.toArray(EMPTY_ARRAY));
3684         f.put("layoutMgr", layoutMgr);
3685         f.put("dispatcher", dispatcher);
3686         f.put("maxSize", maxSize);
3687         f.put("focusCycleRoot", focusCycleRoot);
3688         f.put("containerSerializedDataVersion", containerSerializedDataVersion);
3689         f.put("focusTraversalPolicyProvider", focusTraversalPolicyProvider);
3690         s.writeFields();
3691 
3692         AWTEventMulticaster.save(s, containerListenerK, containerListener);
3693         s.writeObject(null);
3694 
3695         if (focusTraversalPolicy instanceof java.io.Serializable) {
3696             s.writeObject(focusTraversalPolicy);
3697         } else {
3698             s.writeObject(null);
3699         }
3700     }
3701 
3702     /**
3703      * Deserializes this {@code Container} from the specified
3704      * {@code ObjectInputStream}.
3705      * <ul>
3706      *    <li>Reads default serializable fields from the stream.</li>
3707      *    <li>Reads a list of serializable ContainerListener(s) as optional
3708      *        data. If the list is null, no Listeners are installed.</li>
3709      *    <li>Reads this Container's FocusTraversalPolicy, which may be null,
3710      *        as optional data.</li>
3711      * </ul>
3712      *
3713      * @param s the {@code ObjectInputStream} to read
3714      * @serial
3715      * @see #addContainerListener
3716      * @see #writeObject(ObjectOutputStream)
3717      */
3718     private void readObject(ObjectInputStream s)
3719         throws ClassNotFoundException, IOException
3720     {
3721         ObjectInputStream.GetField f = s.readFields();
3722         Component [] tmpComponent = (Component[])f.get("component", EMPTY_ARRAY);
3723         int ncomponents = (Integer) f.get("ncomponents", 0);
3724         component = new java.util.ArrayList<Component>(ncomponents);
3725         for (int i = 0; i < ncomponents; ++i) {
3726             component.add(tmpComponent[i]);
3727         }
3728         layoutMgr = (LayoutManager)f.get("layoutMgr", null);
3729         dispatcher = (LightweightDispatcher)f.get("dispatcher", null);
3730         // Old stream. Doesn't contain maxSize among Component's fields.
3731         if (maxSize == null) {
3732             maxSize = (Dimension)f.get("maxSize", null);
3733         }
3734         focusCycleRoot = f.get("focusCycleRoot", false);
3735         containerSerializedDataVersion = f.get("containerSerializedDataVersion", 1);
3736         focusTraversalPolicyProvider = f.get("focusTraversalPolicyProvider", false);
3737         java.util.List<Component> component = this.component;
3738         for(Component comp : component) {
3739             comp.parent = this;
3740             adjustListeningChildren(AWTEvent.HIERARCHY_EVENT_MASK,
3741                                     comp.numListening(AWTEvent.HIERARCHY_EVENT_MASK));
3742             adjustListeningChildren(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK,
3743                                     comp.numListening(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK));
3744             adjustDescendants(comp.countHierarchyMembers());
3745         }
3746 
3747         Object keyOrNull;
3748         while(null != (keyOrNull = s.readObject())) {
3749             String key = ((String)keyOrNull).intern();
3750 
3751             if (containerListenerK == key) {
3752                 addContainerListener((ContainerListener)(s.readObject()));
3753             } else {
3754                 // skip value for unrecognized key
3755                 s.readObject();
3756             }
3757         }
3758 
3759         try {
3760             Object policy = s.readObject();
3761             if (policy instanceof FocusTraversalPolicy) {
3762                 focusTraversalPolicy = (FocusTraversalPolicy)policy;
3763             }
3764         } catch (java.io.OptionalDataException e) {
3765             // JDK 1.1/1.2/1.3 instances will not have this optional data.
3766             // e.eof will be true to indicate that there is no more data
3767             // available for this object. If e.eof is not true, throw the
3768             // exception as it might have been caused by reasons unrelated to
3769             // focusTraversalPolicy.
3770 
3771             if (!e.eof) {
3772                 throw e;
3773             }
3774         }
3775     }
3776 
3777     /*
3778      * --- Accessibility Support ---
3779      */
3780 
3781     /**
3782      * Inner class of Container used to provide default support for
3783      * accessibility.  This class is not meant to be used directly by
3784      * application developers, but is instead meant only to be
3785      * subclassed by container developers.
3786      * <p>
3787      * The class used to obtain the accessible role for this object,
3788      * as well as implementing many of the methods in the
3789      * AccessibleContainer interface.
3790      * @since 1.3
3791      */
3792     protected class AccessibleAWTContainer extends AccessibleAWTComponent {
3793 
3794         /**
3795          * JDK1.3 serialVersionUID
3796          */
3797         private static final long serialVersionUID = 5081320404842566097L;
3798 
3799         /**
3800          * Returns the number of accessible children in the object.  If all
3801          * of the children of this object implement {@code Accessible},
3802          * then this method should return the number of children of this object.
3803          *
3804          * @return the number of accessible children in the object
3805          */
3806         public int getAccessibleChildrenCount() {
3807             return Container.this.getAccessibleChildrenCount();
3808         }
3809 
3810         /**
3811          * Returns the nth {@code Accessible} child of the object.
3812          *
3813          * @param i zero-based index of child
3814          * @return the nth {@code Accessible} child of the object
3815          */
3816         public Accessible getAccessibleChild(int i) {
3817             return Container.this.getAccessibleChild(i);
3818         }
3819 
3820         /**
3821          * Returns the {@code Accessible} child, if one exists,
3822          * contained at the local coordinate {@code Point}.
3823          *
3824          * @param p the point defining the top-left corner of the
3825          *    {@code Accessible}, given in the coordinate space
3826          *    of the object's parent
3827          * @return the {@code Accessible}, if it exists,
3828          *    at the specified location; else {@code null}
3829          */
3830         public Accessible getAccessibleAt(Point p) {
3831             return Container.this.getAccessibleAt(p);
3832         }
3833 
3834         /**
3835          * Number of PropertyChangeListener objects registered. It's used
3836          * to add/remove ContainerListener to track target Container's state.
3837          */
3838         private transient volatile int propertyListenersCount = 0;
3839 
3840         /**
3841          * The handler to fire {@code PropertyChange}
3842          * when children are added or removed
3843          */
3844         protected ContainerListener accessibleContainerHandler = null;
3845 
3846         /**
3847          * Fire {@code PropertyChange} listener, if one is registered,
3848          * when children are added or removed.
3849          * @since 1.3
3850          */
3851         protected class AccessibleContainerHandler
3852             implements ContainerListener {
3853             public void componentAdded(ContainerEvent e) {
3854                 Component c = e.getChild();
3855                 if (c != null && c instanceof Accessible) {
3856                     AccessibleAWTContainer.this.firePropertyChange(
3857                         AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
3858                         null, ((Accessible) c).getAccessibleContext());
3859                 }
3860             }
3861             public void componentRemoved(ContainerEvent e) {
3862                 Component c = e.getChild();
3863                 if (c != null && c instanceof Accessible) {
3864                     AccessibleAWTContainer.this.firePropertyChange(
3865                         AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
3866                         ((Accessible) c).getAccessibleContext(), null);
3867                 }
3868             }
3869         }
3870 
3871         /**
3872          * Adds a PropertyChangeListener to the listener list.
3873          *
3874          * @param listener  the PropertyChangeListener to be added
3875          */
3876         public void addPropertyChangeListener(PropertyChangeListener listener) {
3877             if (accessibleContainerHandler == null) {
3878                 accessibleContainerHandler = new AccessibleContainerHandler();
3879             }
3880             if (propertyListenersCount++ == 0) {
3881                 Container.this.addContainerListener(accessibleContainerHandler);
3882             }
3883             super.addPropertyChangeListener(listener);
3884         }
3885 
3886         /**
3887          * Remove a PropertyChangeListener from the listener list.
3888          * This removes a PropertyChangeListener that was registered
3889          * for all properties.
3890          *
3891          * @param listener the PropertyChangeListener to be removed
3892          */
3893         public void removePropertyChangeListener(PropertyChangeListener listener) {
3894             if (--propertyListenersCount == 0) {
3895                 Container.this.removeContainerListener(accessibleContainerHandler);
3896             }
3897             super.removePropertyChangeListener(listener);
3898         }
3899 
3900     } // inner class AccessibleAWTContainer
3901 
3902     /**
3903      * Returns the {@code Accessible} child contained at the local
3904      * coordinate {@code Point}, if one exists.  Otherwise
3905      * returns {@code null}.
3906      *
3907      * @param p the point defining the top-left corner of the
3908      *    {@code Accessible}, given in the coordinate space
3909      *    of the object's parent
3910      * @return the {@code Accessible} at the specified location,
3911      *    if it exists; otherwise {@code null}
3912      */
3913     Accessible getAccessibleAt(Point p) {
3914         synchronized (getTreeLock()) {
3915             if (this instanceof Accessible) {
3916                 Accessible a = (Accessible)this;
3917                 AccessibleContext ac = a.getAccessibleContext();
3918                 if (ac != null) {
3919                     AccessibleComponent acmp;
3920                     Point location;
3921                     int nchildren = ac.getAccessibleChildrenCount();
3922                     for (int i=0; i < nchildren; i++) {
3923                         a = ac.getAccessibleChild(i);
3924                         if ((a != null)) {
3925                             ac = a.getAccessibleContext();
3926                             if (ac != null) {
3927                                 acmp = ac.getAccessibleComponent();
3928                                 if ((acmp != null) && (acmp.isShowing())) {
3929                                     location = acmp.getLocation();
3930                                     Point np = new Point(p.x-location.x,
3931                                                          p.y-location.y);
3932                                     if (acmp.contains(np)){
3933                                         return a;
3934                                     }
3935                                 }
3936                             }
3937                         }
3938                     }
3939                 }
3940                 return (Accessible)this;
3941             } else {
3942                 Component ret = this;
3943                 if (!this.contains(p.x,p.y)) {
3944                     ret = null;
3945                 } else {
3946                     int ncomponents = this.getComponentCount();
3947                     for (int i=0; i < ncomponents; i++) {
3948                         Component comp = this.getComponent(i);
3949                         if ((comp != null) && comp.isShowing()) {
3950                             Point location = comp.getLocation();
3951                             if (comp.contains(p.x-location.x,p.y-location.y)) {
3952                                 ret = comp;
3953                             }
3954                         }
3955                     }
3956                 }
3957                 if (ret instanceof Accessible) {
3958                     return (Accessible) ret;
3959                 }
3960             }
3961             return null;
3962         }
3963     }
3964 
3965     /**
3966      * Returns the number of accessible children in the object.  If all
3967      * of the children of this object implement {@code Accessible},
3968      * then this method should return the number of children of this object.
3969      *
3970      * @return the number of accessible children in the object
3971      */
3972     int getAccessibleChildrenCount() {
3973         synchronized (getTreeLock()) {
3974             int count = 0;
3975             Component[] children = this.getComponents();
3976             for (int i = 0; i < children.length; i++) {
3977                 if (children[i] instanceof Accessible) {
3978                     count++;
3979                 }
3980             }
3981             return count;
3982         }
3983     }
3984 
3985     /**
3986      * Returns the nth {@code Accessible} child of the object.
3987      *
3988      * @param i zero-based index of child
3989      * @return the nth {@code Accessible} child of the object
3990      */
3991     Accessible getAccessibleChild(int i) {
3992         synchronized (getTreeLock()) {
3993             Component[] children = this.getComponents();
3994             int count = 0;
3995             for (int j = 0; j < children.length; j++) {
3996                 if (children[j] instanceof Accessible) {
3997                     if (count == i) {
3998                         return (Accessible) children[j];
3999                     } else {
4000                         count++;
4001                     }
4002                 }
4003             }
4004             return null;
4005         }
4006     }
4007 
4008     // ************************** MIXING CODE *******************************
4009 
4010     final void increaseComponentCount(Component c) {
4011         synchronized (getTreeLock()) {
4012             if (!c.isDisplayable()) {
4013                 throw new IllegalStateException(
4014                     "Peer does not exist while invoking the increaseComponentCount() method"
4015                 );
4016             }
4017 
4018             int addHW = 0;
4019             int addLW = 0;
4020 
4021             if (c instanceof Container) {
4022                 addLW = ((Container)c).numOfLWComponents;
4023                 addHW = ((Container)c).numOfHWComponents;
4024             }
4025             if (c.isLightweight()) {
4026                 addLW++;
4027             } else {
4028                 addHW++;
4029             }
4030 
4031             for (Container cont = this; cont != null; cont = cont.getContainer()) {
4032                 cont.numOfLWComponents += addLW;
4033                 cont.numOfHWComponents += addHW;
4034             }
4035         }
4036     }
4037 
4038     final void decreaseComponentCount(Component c) {
4039         synchronized (getTreeLock()) {
4040             if (!c.isDisplayable()) {
4041                 throw new IllegalStateException(
4042                     "Peer does not exist while invoking the decreaseComponentCount() method"
4043                 );
4044             }
4045 
4046             int subHW = 0;
4047             int subLW = 0;
4048 
4049             if (c instanceof Container) {
4050                 subLW = ((Container)c).numOfLWComponents;
4051                 subHW = ((Container)c).numOfHWComponents;
4052             }
4053             if (c.isLightweight()) {
4054                 subLW++;
4055             } else {
4056                 subHW++;
4057             }
4058 
4059             for (Container cont = this; cont != null; cont = cont.getContainer()) {
4060                 cont.numOfLWComponents -= subLW;
4061                 cont.numOfHWComponents -= subHW;
4062             }
4063         }
4064     }
4065 
4066     private int getTopmostComponentIndex() {
4067         checkTreeLock();
4068         if (getComponentCount() > 0) {
4069             return 0;
4070         }
4071         return -1;
4072     }
4073 
4074     private int getBottommostComponentIndex() {
4075         checkTreeLock();
4076         if (getComponentCount() > 0) {
4077             return getComponentCount() - 1;
4078         }
4079         return -1;
4080     }
4081 
4082     /*
4083      * This method is overriden to handle opaque children in non-opaque
4084      * containers.
4085      */
4086     @Override
4087     final Region getOpaqueShape() {
4088         checkTreeLock();
4089         if (isLightweight() && isNonOpaqueForMixing()
4090                 && hasLightweightDescendants())
4091         {
4092             Region s = Region.EMPTY_REGION;
4093             for (int index = 0; index < getComponentCount(); index++) {
4094                 Component c = getComponent(index);
4095                 if (c.isLightweight() && c.isShowing()) {
4096                     s = s.getUnion(c.getOpaqueShape());
4097                 }
4098             }
4099             return s.getIntersection(getNormalShape());
4100         }
4101         return super.getOpaqueShape();
4102     }
4103 
4104     final void recursiveSubtractAndApplyShape(Region shape) {
4105         recursiveSubtractAndApplyShape(shape, getTopmostComponentIndex(), getBottommostComponentIndex());
4106     }
4107 
4108     final void recursiveSubtractAndApplyShape(Region shape, int fromZorder) {
4109         recursiveSubtractAndApplyShape(shape, fromZorder, getBottommostComponentIndex());
4110     }
4111 
4112     final void recursiveSubtractAndApplyShape(Region shape, int fromZorder, int toZorder) {
4113         checkTreeLock();
4114         if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
4115             mixingLog.fine("this = " + this +
4116                 "; shape=" + shape + "; fromZ=" + fromZorder + "; toZ=" + toZorder);
4117         }
4118         if (fromZorder == -1) {
4119             return;
4120         }
4121         if (shape.isEmpty()) {
4122             return;
4123         }
4124         // An invalid container with not-null layout should be ignored
4125         // by the mixing code, the container will be validated later
4126         // and the mixing code will be executed later.
4127         if (getLayout() != null && !isValid()) {
4128             return;
4129         }
4130         for (int index = fromZorder; index <= toZorder; index++) {
4131             Component comp = getComponent(index);
4132             if (!comp.isLightweight()) {
4133                 comp.subtractAndApplyShape(shape);
4134             } else if (comp instanceof Container &&
4135                     ((Container)comp).hasHeavyweightDescendants() && comp.isShowing()) {
4136                 ((Container)comp).recursiveSubtractAndApplyShape(shape);
4137             }
4138         }
4139     }
4140 
4141     final void recursiveApplyCurrentShape() {
4142         recursiveApplyCurrentShape(getTopmostComponentIndex(), getBottommostComponentIndex());
4143     }
4144 
4145     final void recursiveApplyCurrentShape(int fromZorder) {
4146         recursiveApplyCurrentShape(fromZorder, getBottommostComponentIndex());
4147     }
4148 
4149     final void recursiveApplyCurrentShape(int fromZorder, int toZorder) {
4150         checkTreeLock();
4151         if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
4152             mixingLog.fine("this = " + this +
4153                 "; fromZ=" + fromZorder + "; toZ=" + toZorder);
4154         }
4155         if (fromZorder == -1) {
4156             return;
4157         }
4158         // An invalid container with not-null layout should be ignored
4159         // by the mixing code, the container will be validated later
4160         // and the mixing code will be executed later.
4161         if (getLayout() != null && !isValid()) {
4162             return;
4163         }
4164         for (int index = fromZorder; index <= toZorder; index++) {
4165             Component comp = getComponent(index);
4166             if (!comp.isLightweight()) {
4167                 comp.applyCurrentShape();
4168             }
4169             if (comp instanceof Container &&
4170                     ((Container)comp).hasHeavyweightDescendants()) {
4171                 ((Container)comp).recursiveApplyCurrentShape();
4172             }
4173         }
4174     }
4175 
4176     @SuppressWarnings("deprecation")
4177     private void recursiveShowHeavyweightChildren() {
4178         if (!hasHeavyweightDescendants() || !isVisible()) {
4179             return;
4180         }
4181         for (int index = 0; index < getComponentCount(); index++) {
4182             Component comp = getComponent(index);
4183             if (comp.isLightweight()) {
4184                 if  (comp instanceof Container) {
4185                     ((Container)comp).recursiveShowHeavyweightChildren();
4186                 }
4187             } else {
4188                 if (comp.isVisible()) {
4189                     ComponentPeer peer = comp.peer;
4190                     if (peer != null) {
4191                         peer.setVisible(true);
4192                     }
4193                 }
4194             }
4195         }
4196     }
4197 
4198     @SuppressWarnings("deprecation")
4199     private void recursiveHideHeavyweightChildren() {
4200         if (!hasHeavyweightDescendants()) {
4201             return;
4202         }
4203         for (int index = 0; index < getComponentCount(); index++) {
4204             Component comp = getComponent(index);
4205             if (comp.isLightweight()) {
4206                 if  (comp instanceof Container) {
4207                     ((Container)comp).recursiveHideHeavyweightChildren();
4208                 }
4209             } else {
4210                 if (comp.isVisible()) {
4211                     ComponentPeer peer = comp.peer;
4212                     if (peer != null) {
4213                         peer.setVisible(false);
4214                     }
4215                 }
4216             }
4217         }
4218     }
4219 
4220     @SuppressWarnings("deprecation")
4221     private void recursiveRelocateHeavyweightChildren(Point origin) {
4222         for (int index = 0; index < getComponentCount(); index++) {
4223             Component comp = getComponent(index);
4224             if (comp.isLightweight()) {
4225                 if  (comp instanceof Container &&
4226                         ((Container)comp).hasHeavyweightDescendants())
4227                 {
4228                     final Point newOrigin = new Point(origin);
4229                     newOrigin.translate(comp.getX(), comp.getY());
4230                     ((Container)comp).recursiveRelocateHeavyweightChildren(newOrigin);
4231                 }
4232             } else {
4233                 ComponentPeer peer = comp.peer;
4234                 if (peer != null) {
4235                     peer.setBounds(origin.x + comp.getX(), origin.y + comp.getY(),
4236                             comp.getWidth(), comp.getHeight(),
4237                             ComponentPeer.SET_LOCATION);
4238                 }
4239             }
4240         }
4241     }
4242 
4243     /**
4244      * Checks if the container and its direct lightweight containers are
4245      * visible.
4246      *
4247      * Consider the heavyweight container hides or shows the HW descendants
4248      * automatically. Therefore we care of LW containers' visibility only.
4249      *
4250      * This method MUST be invoked under the TreeLock.
4251      */
4252     final boolean isRecursivelyVisibleUpToHeavyweightContainer() {
4253         if (!isLightweight()) {
4254             return true;
4255         }
4256 
4257         for (Container cont = this;
4258                 cont != null && cont.isLightweight();
4259                 cont = cont.getContainer())
4260         {
4261             if (!cont.isVisible()) {
4262                 return false;
4263             }
4264         }
4265         return true;
4266     }
4267 
4268     @Override
4269     void mixOnShowing() {
4270         synchronized (getTreeLock()) {
4271             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
4272                 mixingLog.fine("this = " + this);
4273             }
4274 
4275             boolean isLightweight = isLightweight();
4276 
4277             if (isLightweight && isRecursivelyVisibleUpToHeavyweightContainer()) {
4278                 recursiveShowHeavyweightChildren();
4279             }
4280 
4281             if (!isMixingNeeded()) {
4282                 return;
4283             }
4284 
4285             if (!isLightweight || (isLightweight && hasHeavyweightDescendants())) {
4286                 recursiveApplyCurrentShape();
4287             }
4288 
4289             super.mixOnShowing();
4290         }
4291     }
4292 
4293     @Override
4294     void mixOnHiding(boolean isLightweight) {
4295         synchronized (getTreeLock()) {
4296             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
4297                 mixingLog.fine("this = " + this +
4298                         "; isLightweight=" + isLightweight);
4299             }
4300             if (isLightweight) {
4301                 recursiveHideHeavyweightChildren();
4302             }
4303             super.mixOnHiding(isLightweight);
4304         }
4305     }
4306 
4307     @Override
4308     void mixOnReshaping() {
4309         synchronized (getTreeLock()) {
4310             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
4311                 mixingLog.fine("this = " + this);
4312             }
4313 
4314             boolean isMixingNeeded = isMixingNeeded();
4315 
4316             if (isLightweight() && hasHeavyweightDescendants()) {
4317                 final Point origin = new Point(getX(), getY());
4318                 for (Container cont = getContainer();
4319                         cont != null && cont.isLightweight();
4320                         cont = cont.getContainer())
4321                 {
4322                     origin.translate(cont.getX(), cont.getY());
4323                 }
4324 
4325                 recursiveRelocateHeavyweightChildren(origin);
4326 
4327                 if (!isMixingNeeded) {
4328                     return;
4329                 }
4330 
4331                 recursiveApplyCurrentShape();
4332             }
4333 
4334             if (!isMixingNeeded) {
4335                 return;
4336             }
4337 
4338             super.mixOnReshaping();
4339         }
4340     }
4341 
4342     @Override
4343     void mixOnZOrderChanging(int oldZorder, int newZorder) {
4344         synchronized (getTreeLock()) {
4345             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
4346                 mixingLog.fine("this = " + this +
4347                     "; oldZ=" + oldZorder + "; newZ=" + newZorder);
4348             }
4349 
4350             if (!isMixingNeeded()) {
4351                 return;
4352             }
4353 
4354             boolean becameHigher = newZorder < oldZorder;
4355 
4356             if (becameHigher && isLightweight() && hasHeavyweightDescendants()) {
4357                 recursiveApplyCurrentShape();
4358             }
4359             super.mixOnZOrderChanging(oldZorder, newZorder);
4360         }
4361     }
4362 
4363     @Override
4364     void mixOnValidating() {
4365         synchronized (getTreeLock()) {
4366             if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {
4367                 mixingLog.fine("this = " + this);
4368             }
4369 
4370             if (!isMixingNeeded()) {
4371                 return;
4372             }
4373 
4374             if (hasHeavyweightDescendants()) {
4375                 recursiveApplyCurrentShape();
4376             }
4377 
4378             if (isLightweight() && isNonOpaqueForMixing()) {
4379                 subtractAndApplyShapeBelowMe();
4380             }
4381 
4382             super.mixOnValidating();
4383         }
4384     }
4385 
4386     // ****************** END OF MIXING CODE ********************************
4387 }
4388 
4389 
4390 /**
4391  * Class to manage the dispatching of MouseEvents to the lightweight descendants
4392  * and SunDropTargetEvents to both lightweight and heavyweight descendants
4393  * contained by a native container.
4394  *
4395  * NOTE: the class name is not appropriate anymore, but we cannot change it
4396  * because we must keep serialization compatibility.
4397  *
4398  * @author Timothy Prinzing
4399  */
4400 class LightweightDispatcher implements java.io.Serializable, AWTEventListener {
4401 
4402     /*
4403      * JDK 1.1 serialVersionUID
4404      */
4405     private static final long serialVersionUID = 5184291520170872969L;
4406     /*
4407      * Our own mouse event for when we're dragged over from another hw
4408      * container
4409      */
4410     private static final int  LWD_MOUSE_DRAGGED_OVER = 1500;
4411 
4412     private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.LightweightDispatcher");
4413 
4414     private static final int BUTTONS_DOWN_MASK;
4415 
4416     static {
4417         int[] buttonsDownMask = AWTAccessor.getInputEventAccessor().
4418                 getButtonDownMasks();
4419         int mask = 0;
4420         for (int buttonDownMask : buttonsDownMask) {
4421             mask |= buttonDownMask;
4422         }
4423         BUTTONS_DOWN_MASK = mask;
4424     }
4425 
4426     LightweightDispatcher(Container nativeContainer) {
4427         this.nativeContainer = nativeContainer;
4428         mouseEventTarget = new WeakReference<>(null);
4429         targetLastEntered = new WeakReference<>(null);
4430         targetLastEnteredDT = new WeakReference<>(null);
4431         eventMask = 0;
4432     }
4433 
4434     /*
4435      * Clean up any resources allocated when dispatcher was created;
4436      * should be called from Container.removeNotify
4437      */
4438     void dispose() {
4439         //System.out.println("Disposing lw dispatcher");
4440         stopListeningForOtherDrags();
4441         mouseEventTarget.clear();
4442         targetLastEntered.clear();
4443         targetLastEnteredDT.clear();
4444     }
4445 
4446     /**
4447      * Enables events to subcomponents.
4448      */
4449     void enableEvents(long events) {
4450         eventMask |= events;
4451     }
4452 
4453     /**
4454      * Dispatches an event to a sub-component if necessary, and
4455      * returns whether or not the event was forwarded to a
4456      * sub-component.
4457      *
4458      * @param e the event
4459      */
4460     boolean dispatchEvent(AWTEvent e) {
4461         boolean ret = false;
4462 
4463         /*
4464          * Fix for BugTraq Id 4389284.
4465          * Dispatch SunDropTargetEvents regardless of eventMask value.
4466          * Do not update cursor on dispatching SunDropTargetEvents.
4467          */
4468         if (e instanceof SunDropTargetEvent) {
4469 
4470             SunDropTargetEvent sdde = (SunDropTargetEvent) e;
4471             ret = processDropTargetEvent(sdde);
4472 
4473         } else {
4474             if (e instanceof MouseEvent && (eventMask & MOUSE_MASK) != 0) {
4475                 MouseEvent me = (MouseEvent) e;
4476                 ret = processMouseEvent(me);
4477             }
4478 
4479             if (e.getID() == MouseEvent.MOUSE_MOVED) {
4480                 nativeContainer.updateCursorImmediately();
4481             }
4482         }
4483 
4484         return ret;
4485     }
4486 
4487     /* This method effectively returns whether or not a mouse button was down
4488      * just BEFORE the event happened.  A better method name might be
4489      * wasAMouseButtonDownBeforeThisEvent().
4490      */
4491     private boolean isMouseGrab(MouseEvent e) {
4492         int modifiers = e.getModifiersEx();
4493 
4494         if (e.getID() == MouseEvent.MOUSE_PRESSED
4495                 || e.getID() == MouseEvent.MOUSE_RELEASED) {
4496             modifiers ^= InputEvent.getMaskForButton(e.getButton());
4497         }
4498         /* modifiers now as just before event */
4499         return ((modifiers & BUTTONS_DOWN_MASK) != 0);
4500     }
4501 
4502     /**
4503      * This method attempts to distribute a mouse event to a lightweight
4504      * component.  It tries to avoid doing any unnecessary probes down
4505      * into the component tree to minimize the overhead of determining
4506      * where to route the event, since mouse movement events tend to
4507      * come in large and frequent amounts.
4508      */
4509     private boolean processMouseEvent(MouseEvent e) {
4510         int id = e.getID();
4511         Component mouseOver =   // sensitive to mouse events
4512             nativeContainer.getMouseEventTarget(e.getX(), e.getY(),
4513                                                 Container.INCLUDE_SELF);
4514 
4515         trackMouseEnterExit(mouseOver, e);
4516 
4517         Component met = mouseEventTarget.get();
4518         // 4508327 : MOUSE_CLICKED should only go to the recipient of
4519         // the accompanying MOUSE_PRESSED, so don't reset mouseEventTarget on a
4520         // MOUSE_CLICKED.
4521         if (!isMouseGrab(e) && id != MouseEvent.MOUSE_CLICKED) {
4522             met = (mouseOver != nativeContainer) ? mouseOver : null;
4523             mouseEventTarget = new WeakReference<>(met);
4524         }
4525 
4526         if (met != null) {
4527             switch (id) {
4528                 case MouseEvent.MOUSE_ENTERED:
4529                 case MouseEvent.MOUSE_EXITED:
4530                     break;
4531                 case MouseEvent.MOUSE_PRESSED:
4532                     retargetMouseEvent(met, id, e);
4533                     break;
4534                 case MouseEvent.MOUSE_RELEASED:
4535                     retargetMouseEvent(met, id, e);
4536                     break;
4537                 case MouseEvent.MOUSE_CLICKED:
4538                     // 4508327: MOUSE_CLICKED should never be dispatched to a Component
4539                     // other than that which received the MOUSE_PRESSED event.  If the
4540                     // mouse is now over a different Component, don't dispatch the event.
4541                     // The previous fix for a similar problem was associated with bug
4542                     // 4155217.
4543                     if (mouseOver == met) {
4544                         retargetMouseEvent(mouseOver, id, e);
4545                     }
4546                     break;
4547                 case MouseEvent.MOUSE_MOVED:
4548                     retargetMouseEvent(met, id, e);
4549                     break;
4550                 case MouseEvent.MOUSE_DRAGGED:
4551                     if (isMouseGrab(e)) {
4552                         retargetMouseEvent(met, id, e);
4553                     }
4554                     break;
4555                 case MouseEvent.MOUSE_WHEEL:
4556                     // This may send it somewhere that doesn't have MouseWheelEvents
4557                     // enabled.  In this case, Component.dispatchEventImpl() will
4558                     // retarget the event to a parent that DOES have the events enabled.
4559                     if (eventLog.isLoggable(PlatformLogger.Level.FINEST) && (mouseOver != null)) {
4560                         eventLog.finest("retargeting mouse wheel to " +
4561                                 mouseOver.getName() + ", " +
4562                                 mouseOver.getClass());
4563                     }
4564                     retargetMouseEvent(mouseOver, id, e);
4565                     break;
4566             }
4567             //Consuming of wheel events is implemented in "retargetMouseEvent".
4568             if (id != MouseEvent.MOUSE_WHEEL) {
4569                 e.consume();
4570             }
4571         }
4572         return e.isConsumed();
4573     }
4574 
4575     private boolean processDropTargetEvent(SunDropTargetEvent e) {
4576         int id = e.getID();
4577         int x = e.getX();
4578         int y = e.getY();
4579 
4580         /*
4581          * Fix for BugTraq ID 4395290.
4582          * It is possible that SunDropTargetEvent's Point is outside of the
4583          * native container bounds. In this case we truncate coordinates.
4584          */
4585         if (!nativeContainer.contains(x, y)) {
4586             final Dimension d = nativeContainer.getSize();
4587             if (d.width <= x) {
4588                 x = d.width - 1;
4589             } else if (x < 0) {
4590                 x = 0;
4591             }
4592             if (d.height <= y) {
4593                 y = d.height - 1;
4594             } else if (y < 0) {
4595                 y = 0;
4596             }
4597         }
4598         Component mouseOver =   // not necessarily sensitive to mouse events
4599             nativeContainer.getDropTargetEventTarget(x, y,
4600                                                      Container.INCLUDE_SELF);
4601         trackMouseEnterExit(mouseOver, e);
4602 
4603         if (mouseOver != nativeContainer && mouseOver != null) {
4604             switch (id) {
4605             case SunDropTargetEvent.MOUSE_ENTERED:
4606             case SunDropTargetEvent.MOUSE_EXITED:
4607                 break;
4608             default:
4609                 retargetMouseEvent(mouseOver, id, e);
4610                 e.consume();
4611                 break;
4612             }
4613         }
4614         return e.isConsumed();
4615     }
4616 
4617     /*
4618      * Generates dnd enter/exit events as mouse moves over lw components
4619      * @param targetOver       Target mouse is over (including native container)
4620      * @param e                SunDropTarget mouse event in native container
4621      */
4622     private void trackDropTargetEnterExit(Component targetOver, MouseEvent e) {
4623         int id = e.getID();
4624         if (id == MouseEvent.MOUSE_ENTERED && isMouseDTInNativeContainer) {
4625             // This can happen if a lightweight component which initiated the
4626             // drag has an associated drop target. MOUSE_ENTERED comes when the
4627             // mouse is in the native container already. To propagate this event
4628             // properly we should null out targetLastEntered.
4629             targetLastEnteredDT.clear();
4630         } else if (id == MouseEvent.MOUSE_ENTERED) {
4631             isMouseDTInNativeContainer = true;
4632         } else if (id == MouseEvent.MOUSE_EXITED) {
4633             isMouseDTInNativeContainer = false;
4634         }
4635         Component tle = retargetMouseEnterExit(targetOver, e,
4636                                                      targetLastEnteredDT.get(),
4637                                                      isMouseDTInNativeContainer);
4638         targetLastEnteredDT = new WeakReference<>(tle);
4639     }
4640 
4641     /*
4642      * Generates enter/exit events as mouse moves over lw components
4643      * @param targetOver        Target mouse is over (including native container)
4644      * @param e                 Mouse event in native container
4645      */
4646     private void trackMouseEnterExit(Component targetOver, MouseEvent e) {
4647         if (e instanceof SunDropTargetEvent) {
4648             trackDropTargetEnterExit(targetOver, e);
4649             return;
4650         }
4651         int id = e.getID();
4652 
4653         if ( id != MouseEvent.MOUSE_EXITED &&
4654              id != MouseEvent.MOUSE_DRAGGED &&
4655              id != LWD_MOUSE_DRAGGED_OVER &&
4656                 !isMouseInNativeContainer) {
4657             // any event but an exit or drag means we're in the native container
4658             isMouseInNativeContainer = true;
4659             startListeningForOtherDrags();
4660         } else if (id == MouseEvent.MOUSE_EXITED) {
4661             isMouseInNativeContainer = false;
4662             stopListeningForOtherDrags();
4663         }
4664         Component tle = retargetMouseEnterExit(targetOver, e,
4665                                                    targetLastEntered.get(),
4666                                                    isMouseInNativeContainer);
4667         targetLastEntered = new WeakReference<>(tle);
4668     }
4669 
4670     private Component retargetMouseEnterExit(Component targetOver, MouseEvent e,
4671                                              Component lastEntered,
4672                                              boolean inNativeContainer) {
4673         int id = e.getID();
4674         Component targetEnter = inNativeContainer ? targetOver : null;
4675 
4676         if (lastEntered != targetEnter) {
4677             if (lastEntered != null) {
4678                 retargetMouseEvent(lastEntered, MouseEvent.MOUSE_EXITED, e);
4679             }
4680             if (id == MouseEvent.MOUSE_EXITED) {
4681                 // consume native exit event if we generate one
4682                 e.consume();
4683             }
4684 
4685             if (targetEnter != null) {
4686                 retargetMouseEvent(targetEnter, MouseEvent.MOUSE_ENTERED, e);
4687             }
4688             if (id == MouseEvent.MOUSE_ENTERED) {
4689                 // consume native enter event if we generate one
4690                 e.consume();
4691             }
4692         }
4693         return targetEnter;
4694     }
4695 
4696     /*
4697      * Listens to global mouse drag events so even drags originating
4698      * from other heavyweight containers will generate enter/exit
4699      * events in this container
4700      */
4701     private void startListeningForOtherDrags() {
4702         //System.out.println("Adding AWTEventListener");
4703         java.security.AccessController.doPrivileged(
4704             new java.security.PrivilegedAction<Object>() {
4705                 public Object run() {
4706                     nativeContainer.getToolkit().addAWTEventListener(
4707                         LightweightDispatcher.this,
4708                         AWTEvent.MOUSE_EVENT_MASK |
4709                         AWTEvent.MOUSE_MOTION_EVENT_MASK);
4710                     return null;
4711                 }
4712             }
4713         );
4714     }
4715 
4716     private void stopListeningForOtherDrags() {
4717         //System.out.println("Removing AWTEventListener");
4718         java.security.AccessController.doPrivileged(
4719             new java.security.PrivilegedAction<Object>() {
4720                 public Object run() {
4721                     nativeContainer.getToolkit().removeAWTEventListener(LightweightDispatcher.this);
4722                     return null;
4723                 }
4724             }
4725         );
4726     }
4727 
4728     /*
4729      * (Implementation of AWTEventListener)
4730      * Listen for drag events posted in other hw components so we can
4731      * track enter/exit regardless of where a drag originated
4732      */
4733     @SuppressWarnings("deprecation")
4734     public void eventDispatched(AWTEvent e) {
4735         boolean isForeignDrag = (e instanceof MouseEvent) &&
4736                                 !(e instanceof SunDropTargetEvent) &&
4737                                 (e.id == MouseEvent.MOUSE_DRAGGED) &&
4738                                 (e.getSource() != nativeContainer);
4739 
4740         if (!isForeignDrag) {
4741             // only interested in drags from other hw components
4742             return;
4743         }
4744 
4745         MouseEvent      srcEvent = (MouseEvent)e;
4746         MouseEvent      me;
4747 
4748         synchronized (nativeContainer.getTreeLock()) {
4749             Component srcComponent = srcEvent.getComponent();
4750 
4751             // component may have disappeared since drag event posted
4752             // (i.e. Swing hierarchical menus)
4753             if ( !srcComponent.isShowing() ) {
4754                 return;
4755             }
4756 
4757             // see 5083555
4758             // check if srcComponent is in any modal blocked window
4759             Component c = nativeContainer;
4760             while ((c != null) && !(c instanceof Window)) {
4761                 c = c.getParent_NoClientCode();
4762             }
4763             if ((c == null) || ((Window)c).isModalBlocked()) {
4764                 return;
4765             }
4766 
4767             //
4768             // create an internal 'dragged-over' event indicating
4769             // we are being dragged over from another hw component
4770             //
4771             me = new MouseEvent(nativeContainer,
4772                                LWD_MOUSE_DRAGGED_OVER,
4773                                srcEvent.getWhen(),
4774                                srcEvent.getModifiersEx() | srcEvent.getModifiers(),
4775                                srcEvent.getX(),
4776                                srcEvent.getY(),
4777                                srcEvent.getXOnScreen(),
4778                                srcEvent.getYOnScreen(),
4779                                srcEvent.getClickCount(),
4780                                srcEvent.isPopupTrigger(),
4781                                srcEvent.getButton());
4782             MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
4783             meAccessor.setCausedByTouchEvent(me,
4784                 meAccessor.isCausedByTouchEvent(srcEvent));
4785             ((AWTEvent)srcEvent).copyPrivateDataInto(me);
4786             // translate coordinates to this native container
4787             final Point ptSrcOrigin = srcComponent.getLocationOnScreen();
4788 
4789             if (AppContext.getAppContext() != nativeContainer.appContext) {
4790                 final MouseEvent mouseEvent = me;
4791                 Runnable r = new Runnable() {
4792                         public void run() {
4793                             if (!nativeContainer.isShowing() ) {
4794                                 return;
4795                             }
4796 
4797                             Point       ptDstOrigin = nativeContainer.getLocationOnScreen();
4798                             mouseEvent.translatePoint(ptSrcOrigin.x - ptDstOrigin.x,
4799                                               ptSrcOrigin.y - ptDstOrigin.y );
4800                             Component targetOver =
4801                                 nativeContainer.getMouseEventTarget(mouseEvent.getX(),
4802                                                                     mouseEvent.getY(),
4803                                                                     Container.INCLUDE_SELF);
4804                             trackMouseEnterExit(targetOver, mouseEvent);
4805                         }
4806                     };
4807                 SunToolkit.executeOnEventHandlerThread(nativeContainer, r);
4808                 return;
4809             } else {
4810                 if (!nativeContainer.isShowing() ) {
4811                     return;
4812                 }
4813 
4814                 Point   ptDstOrigin = nativeContainer.getLocationOnScreen();
4815                 me.translatePoint( ptSrcOrigin.x - ptDstOrigin.x, ptSrcOrigin.y - ptDstOrigin.y );
4816             }
4817         }
4818         //System.out.println("Track event: " + me);
4819         // feed the 'dragged-over' event directly to the enter/exit
4820         // code (not a real event so don't pass it to dispatchEvent)
4821         Component targetOver =
4822             nativeContainer.getMouseEventTarget(me.getX(), me.getY(),
4823                                                 Container.INCLUDE_SELF);
4824         trackMouseEnterExit(targetOver, me);
4825     }
4826 
4827     /**
4828      * Sends a mouse event to the current mouse event recipient using
4829      * the given event (sent to the windowed host) as a srcEvent.  If
4830      * the mouse event target is still in the component tree, the
4831      * coordinates of the event are translated to those of the target.
4832      * If the target has been removed, we don't bother to send the
4833      * message.
4834      */
4835     @SuppressWarnings("deprecation")
4836     void retargetMouseEvent(Component target, int id, MouseEvent e) {
4837         if (target == null) {
4838             return; // mouse is over another hw component or target is disabled
4839         }
4840 
4841         int x = e.getX(), y = e.getY();
4842         Component component;
4843 
4844         for(component = target;
4845             component != null && component != nativeContainer;
4846             component = component.getParent()) {
4847             x -= component.x;
4848             y -= component.y;
4849         }
4850         MouseEvent retargeted;
4851         if (component != null) {
4852             if (e instanceof SunDropTargetEvent) {
4853                 retargeted = new SunDropTargetEvent(target,
4854                                                     id,
4855                                                     x,
4856                                                     y,
4857                                                     ((SunDropTargetEvent)e).getDispatcher());
4858             } else if (id == MouseEvent.MOUSE_WHEEL) {
4859                 retargeted = new MouseWheelEvent(target,
4860                                       id,
4861                                        e.getWhen(),
4862                                        e.getModifiersEx() | e.getModifiers(),
4863                                        x,
4864                                        y,
4865                                        e.getXOnScreen(),
4866                                        e.getYOnScreen(),
4867                                        e.getClickCount(),
4868                                        e.isPopupTrigger(),
4869                                        ((MouseWheelEvent)e).getScrollType(),
4870                                        ((MouseWheelEvent)e).getScrollAmount(),
4871                                        ((MouseWheelEvent)e).getWheelRotation(),
4872                                        ((MouseWheelEvent)e).getPreciseWheelRotation());
4873             }
4874             else {
4875                 retargeted = new MouseEvent(target,
4876                                             id,
4877                                             e.getWhen(),
4878                                             e.getModifiersEx() | e.getModifiers(),
4879                                             x,
4880                                             y,
4881                                             e.getXOnScreen(),
4882                                             e.getYOnScreen(),
4883                                             e.getClickCount(),
4884                                             e.isPopupTrigger(),
4885                                             e.getButton());
4886                 MouseEventAccessor meAccessor = AWTAccessor.getMouseEventAccessor();
4887                 meAccessor.setCausedByTouchEvent(retargeted,
4888                     meAccessor.isCausedByTouchEvent(e));
4889             }
4890 
4891             ((AWTEvent)e).copyPrivateDataInto(retargeted);
4892 
4893             if (target == nativeContainer) {
4894                 // avoid recursively calling LightweightDispatcher...
4895                 ((Container)target).dispatchEventToSelf(retargeted);
4896             } else {
4897                 assert AppContext.getAppContext() == target.appContext;
4898 
4899                 if (nativeContainer.modalComp != null) {
4900                     if (((Container)nativeContainer.modalComp).isAncestorOf(target)) {
4901                         target.dispatchEvent(retargeted);
4902                     } else {
4903                         e.consume();
4904                     }
4905                 } else {
4906                     target.dispatchEvent(retargeted);
4907                 }
4908             }
4909             if (id == MouseEvent.MOUSE_WHEEL && retargeted.isConsumed()) {
4910                 //An exception for wheel bubbling to the native system.
4911                 //In "processMouseEvent" total event consuming for wheel events is skipped.
4912                 //Protection from bubbling of Java-accepted wheel events.
4913                 e.consume();
4914             }
4915         }
4916     }
4917 
4918     // --- member variables -------------------------------
4919 
4920     /**
4921      * The windowed container that might be hosting events for
4922      * subcomponents.
4923      */
4924     private Container nativeContainer;
4925 
4926     /**
4927      * This variable is not used, but kept for serialization compatibility
4928      */
4929     private Component focus;
4930 
4931     /**
4932      * The current subcomponent being hosted by this windowed
4933      * component that has events being forwarded to it.  If this
4934      * is null, there are currently no events being forwarded to
4935      * a subcomponent.
4936      */
4937     private transient WeakReference<Component> mouseEventTarget;
4938 
4939     /**
4940      * The last component entered by the {@code MouseEvent}.
4941      */
4942     private transient  WeakReference<Component> targetLastEntered;
4943 
4944     /**
4945      * The last component entered by the {@code SunDropTargetEvent}.
4946      */
4947     private transient  WeakReference<Component> targetLastEnteredDT;
4948 
4949     /**
4950      * Is the mouse over the native container.
4951      */
4952     private transient boolean isMouseInNativeContainer = false;
4953 
4954     /**
4955      * Is DnD over the native container.
4956      */
4957     private transient boolean isMouseDTInNativeContainer = false;
4958 
4959     /**
4960      * This variable is not used, but kept for serialization compatibility
4961      */
4962     private Cursor nativeCursor;
4963 
4964     /**
4965      * The event mask for contained lightweight components.  Lightweight
4966      * components need a windowed container to host window-related
4967      * events.  This separate mask indicates events that have been
4968      * requested by contained lightweight components without effecting
4969      * the mask of the windowed component itself.
4970      */
4971     private long eventMask;
4972 
4973     /**
4974      * The kind of events routed to lightweight components from windowed
4975      * hosts.
4976      */
4977     private static final long PROXY_EVENT_MASK =
4978         AWTEvent.FOCUS_EVENT_MASK |
4979         AWTEvent.KEY_EVENT_MASK |
4980         AWTEvent.MOUSE_EVENT_MASK |
4981         AWTEvent.MOUSE_MOTION_EVENT_MASK |
4982         AWTEvent.MOUSE_WHEEL_EVENT_MASK;
4983 
4984     private static final long MOUSE_MASK =
4985         AWTEvent.MOUSE_EVENT_MASK |
4986         AWTEvent.MOUSE_MOTION_EVENT_MASK |
4987         AWTEvent.MOUSE_WHEEL_EVENT_MASK;
4988 }