1 /*
   2  * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package javax.swing;
  26 
  27 import java.awt.Component;
  28 import java.util.ArrayList;
  29 import java.util.Hashtable;
  30 import java.awt.Color;
  31 import java.awt.Graphics;
  32 import java.awt.Rectangle;
  33 import sun.awt.SunToolkit;
  34 
  35 import javax.accessibility.*;
  36 
  37 /**
  38  * <code>JLayeredPane</code> adds depth to a JFC/Swing container,
  39  * allowing components to overlap each other when needed.
  40  * An <code>Integer</code> object specifies each component's depth in the
  41  * container, where higher-numbered components sit &quot;on top&quot; of other
  42  * components.
  43  * For task-oriented documentation and examples of using layered panes see
  44  * <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html">How to Use a Layered Pane</a>,
  45  * a section in <em>The Java Tutorial</em>.
  46  *
  47  * <TABLE STYLE="FLOAT:RIGHT" BORDER="0" SUMMARY="layout">
  48  * <TR>
  49  *   <TD ALIGN="CENTER">
  50  *     <P STYLE="TEXT-ALIGN:CENTER"><IMG SRC="doc-files/JLayeredPane-1.gif"
  51  *     alt="The following text describes this image."
  52  *     WIDTH="269" HEIGHT="264" STYLE="FLOAT:BOTTOM; BORDER=0">
  53  *   </TD>
  54  * </TR>
  55  * </TABLE>
  56  * For convenience, <code>JLayeredPane</code> divides the depth-range
  57  * into several different layers. Putting a component into one of those
  58  * layers makes it easy to ensure that components overlap properly,
  59  * without having to worry about specifying numbers for specific depths:
  60  * <DL>
  61  *    <DT>DEFAULT_LAYER</DT>
  62  *         <DD>The standard layer, where most components go. This the bottommost
  63  *         layer.
  64  *    <DT>PALETTE_LAYER</DT>
  65  *         <DD>The palette layer sits over the default layer. Useful for floating
  66  *         toolbars and palettes, so they can be positioned above other components.
  67  *    <DT>MODAL_LAYER</DT>
  68  *         <DD>The layer used for modal dialogs. They will appear on top of any
  69  *         toolbars, palettes, or standard components in the container.
  70  *    <DT>POPUP_LAYER</DT>
  71  *         <DD>The popup layer displays above dialogs. That way, the popup windows
  72  *         associated with combo boxes, tooltips, and other help text will appear
  73  *         above the component, palette, or dialog that generated them.
  74  *    <DT>DRAG_LAYER</DT>
  75  *         <DD>When dragging a component, reassigning it to the drag layer ensures
  76  *         that it is positioned over every other component in the container. When
  77  *         finished dragging, it can be reassigned to its normal layer.
  78  * </DL>
  79  * The <code>JLayeredPane</code> methods <code>moveToFront(Component)</code>,
  80  * <code>moveToBack(Component)</code> and <code>setPosition</code> can be used
  81  * to reposition a component within its layer. The <code>setLayer</code> method
  82  * can also be used to change the component's current layer.
  83  *
  84  * <h2>Details</h2>
  85  * <code>JLayeredPane</code> manages its list of children like
  86  * <code>Container</code>, but allows for the definition of a several
  87  * layers within itself. Children in the same layer are managed exactly
  88  * like the normal <code>Container</code> object,
  89  * with the added feature that when children components overlap, children
  90  * in higher layers display above the children in lower layers.
  91  * <p>
  92  * Each layer is a distinct integer number. The layer attribute can be set
  93  * on a <code>Component</code> by passing an <code>Integer</code>
  94  * object during the add call.<br> For example:
  95  * <PRE>
  96  *     layeredPane.add(child, JLayeredPane.DEFAULT_LAYER);
  97  * or
  98  *     layeredPane.add(child, new Integer(10));
  99  * </PRE>
 100  * The layer attribute can also be set on a Component by calling<PRE>
 101  *     layeredPaneParent.setLayer(child, 10)</PRE>
 102  * on the <code>JLayeredPane</code> that is the parent of component. The layer
 103  * should be set <i>before</i> adding the child to the parent.
 104  * <p>
 105  * Higher number layers display above lower number layers. So, using
 106  * numbers for the layers and letters for individual components, a
 107  * representative list order would look like this:<PRE>
 108  *       5a, 5b, 5c, 2a, 2b, 2c, 1a </PRE>
 109  * where the leftmost components are closest to the top of the display.
 110  * <p>
 111  * A component can be moved to the top or bottom position within its
 112  * layer by calling <code>moveToFront</code> or <code>moveToBack</code>.
 113  * <p>
 114  * The position of a component within a layer can also be specified directly.
 115  * Valid positions range from 0 up to one less than the number of
 116  * components in that layer. A value of -1 indicates the bottommost
 117  * position. A value of 0 indicates the topmost position. Unlike layer
 118  * numbers, higher position values are <i>lower</i> in the display.
 119  * <blockquote>
 120  * <b>Note:</b> This sequence (defined by java.awt.Container) is the reverse
 121  * of the layer numbering sequence. Usually though, you will use <code>moveToFront</code>,
 122  * <code>moveToBack</code>, and <code>setLayer</code>.
 123  * </blockquote>
 124  * Here are some examples using the method add(Component, layer, position):
 125  * Calling add(5x, 5, -1) results in:<PRE>
 126  *       5a, 5b, 5c, 5x, 2a, 2b, 2c, 1a </PRE>
 127  *
 128  * Calling add(5z, 5, 2) results in:<PRE>
 129  *       5a, 5b, 5z, 5c, 5x, 2a, 2b, 2c, 1a </PRE>
 130  *
 131  * Calling add(3a, 3, 7) results in:<PRE>
 132  *       5a, 5b, 5z, 5c, 5x, 3a, 2a, 2b, 2c, 1a </PRE>
 133  *
 134  * Using normal paint/event mechanics results in 1a appearing at the bottom
 135  * and 5a being above all other components.
 136  * <p>
 137  * <b>Note:</b> that these layers are simply a logical construct and LayoutManagers
 138  * will affect all child components of this container without regard for
 139  * layer settings.
 140  * <p>
 141  * <strong>Warning:</strong> Swing is not thread safe. For more
 142  * information see <a
 143  * href="package-summary.html#threading">Swing's Threading
 144  * Policy</a>.
 145  * <p>
 146  * <strong>Warning:</strong>
 147  * Serialized objects of this class will not be compatible with
 148  * future Swing releases. The current serialization support is
 149  * appropriate for short term storage or RMI between applications running
 150  * the same version of Swing.  As of 1.4, support for long term storage
 151  * of all JavaBeans&trade;
 152  * has been added to the <code>java.beans</code> package.
 153  * Please see {@link java.beans.XMLEncoder}.
 154  *
 155  * @author David Kloba
 156  * @since 1.2
 157  */
 158 @SuppressWarnings("serial")
 159 public class JLayeredPane extends JComponent implements Accessible {
 160     /// Watch the values in getObjectForLayer()
 161     /** Convenience object defining the Default layer. Equivalent to new Integer(0).*/
 162     public final static Integer DEFAULT_LAYER = 0;
 163     /** Convenience object defining the Palette layer. Equivalent to new Integer(100).*/
 164     public final static Integer PALETTE_LAYER = 100;
 165     /** Convenience object defining the Modal layer. Equivalent to new Integer(200).*/
 166     public final static Integer MODAL_LAYER = 200;
 167     /** Convenience object defining the Popup layer. Equivalent to new Integer(300).*/
 168     public final static Integer POPUP_LAYER = 300;
 169     /** Convenience object defining the Drag layer. Equivalent to new Integer(400).*/
 170     public final static Integer DRAG_LAYER = 400;
 171     /** Convenience object defining the Frame Content layer.
 172       * This layer is normally only use to position the contentPane and menuBar
 173       * components of JFrame.
 174       * Equivalent to new Integer(-30000).
 175       * @see JFrame
 176       */
 177     public final static Integer FRAME_CONTENT_LAYER = new Integer(-30000);
 178 
 179     /** Bound property */
 180     public final static String LAYER_PROPERTY = "layeredContainerLayer";
 181     // Hashtable to store layer values for non-JComponent components
 182     private Hashtable<Component,Integer> componentToLayer;
 183     private boolean optimizedDrawingPossible = true;
 184 
 185 
 186 //////////////////////////////////////////////////////////////////////////////
 187 //// Container Override methods
 188 //////////////////////////////////////////////////////////////////////////////
 189     /** Create a new JLayeredPane */
 190     public JLayeredPane() {
 191         setLayout(null);
 192     }
 193 
 194     private void validateOptimizedDrawing() {
 195         boolean layeredComponentFound = false;
 196         synchronized(getTreeLock()) {
 197             Integer layer;
 198 
 199             for (Component c : getComponents()) {
 200                 layer = null;
 201 
 202                 if(SunToolkit.isInstanceOf(c, "javax.swing.JInternalFrame") ||
 203                        (c instanceof JComponent &&
 204                         (layer = (Integer)((JComponent)c).
 205                                      getClientProperty(LAYER_PROPERTY)) != null))
 206                 {
 207                     if(layer != null && layer.equals(FRAME_CONTENT_LAYER))
 208                         continue;
 209                     layeredComponentFound = true;
 210                     break;
 211                 }
 212             }
 213         }
 214 
 215         if(layeredComponentFound)
 216             optimizedDrawingPossible = false;
 217         else
 218             optimizedDrawingPossible = true;
 219     }
 220 
 221     protected void addImpl(Component comp, Object constraints, int index) {
 222         int layer;
 223         int pos;
 224 
 225         if(constraints instanceof Integer) {
 226             layer = ((Integer)constraints).intValue();
 227             setLayer(comp, layer);
 228         } else
 229             layer = getLayer(comp);
 230 
 231         pos = insertIndexForLayer(layer, index);
 232         super.addImpl(comp, constraints, pos);
 233         comp.validate();
 234         comp.repaint();
 235         validateOptimizedDrawing();
 236     }
 237 
 238     /**
 239      * Remove the indexed component from this pane.
 240      * This is the absolute index, ignoring layers.
 241      *
 242      * @param index  an int specifying the component to remove
 243      * @see #getIndexOf
 244      */
 245     public void remove(int index) {
 246         Component c = getComponent(index);
 247         super.remove(index);
 248         if (c != null && !(c instanceof JComponent)) {
 249             getComponentToLayer().remove(c);
 250         }
 251         validateOptimizedDrawing();
 252     }
 253 
 254     /**
 255      * Removes all the components from this container.
 256      *
 257      * @since 1.5
 258      */
 259     public void removeAll() {
 260         Component[] children = getComponents();
 261         Hashtable<Component, Integer> cToL = getComponentToLayer();
 262         for (int counter = children.length - 1; counter >= 0; counter--) {
 263             Component c = children[counter];
 264             if (c != null && !(c instanceof JComponent)) {
 265                 cToL.remove(c);
 266             }
 267         }
 268         super.removeAll();
 269     }
 270 
 271     /**
 272      * Returns false if components in the pane can overlap, which makes
 273      * optimized drawing impossible. Otherwise, returns true.
 274      *
 275      * @return false if components can overlap, else true
 276      * @see JComponent#isOptimizedDrawingEnabled
 277      */
 278     public boolean isOptimizedDrawingEnabled() {
 279         return optimizedDrawingPossible;
 280     }
 281 
 282 
 283 //////////////////////////////////////////////////////////////////////////////
 284 //// New methods for managing layers
 285 //////////////////////////////////////////////////////////////////////////////
 286     /** Sets the layer property on a JComponent. This method does not cause
 287       * any side effects like setLayer() (painting, add/remove, etc).
 288       * Normally you should use the instance method setLayer(), in order to
 289       * get the desired side-effects (like repainting).
 290       *
 291       * @param c      the JComponent to move
 292       * @param layer  an int specifying the layer to move it to
 293       * @see #setLayer
 294       */
 295     public static void putLayer(JComponent c, int layer) {
 296         /// MAKE SURE THIS AND setLayer(Component c, int layer, int position)  are SYNCED
 297         c.putClientProperty(LAYER_PROPERTY, layer);
 298     }
 299 
 300     /** Gets the layer property for a JComponent, it
 301       * does not cause any side effects like setLayer(). (painting, add/remove, etc)
 302       * Normally you should use the instance method getLayer().
 303       *
 304       * @param c  the JComponent to check
 305       * @return   an int specifying the component's layer
 306       */
 307     public static int getLayer(JComponent c) {
 308         Integer i;
 309         if((i = (Integer)c.getClientProperty(LAYER_PROPERTY)) != null)
 310             return i.intValue();
 311         return DEFAULT_LAYER.intValue();
 312     }
 313 
 314     /** Convenience method that returns the first JLayeredPane which
 315       * contains the specified component. Note that all JFrames have a
 316       * JLayeredPane at their root, so any component in a JFrame will
 317       * have a JLayeredPane parent.
 318       *
 319       * @param c the Component to check
 320       * @return the JLayeredPane that contains the component, or
 321       *         null if no JLayeredPane is found in the component
 322       *         hierarchy
 323       * @see JFrame
 324       * @see JRootPane
 325       */
 326     public static JLayeredPane getLayeredPaneAbove(Component c) {
 327         if(c == null) return null;
 328 
 329         Component parent = c.getParent();
 330         while(parent != null && !(parent instanceof JLayeredPane))
 331             parent = parent.getParent();
 332         return (JLayeredPane)parent;
 333     }
 334 
 335     /** Sets the layer attribute on the specified component,
 336       * making it the bottommost component in that layer.
 337       * Should be called before adding to parent.
 338       *
 339       * @param c     the Component to set the layer for
 340       * @param layer an int specifying the layer to set, where
 341       *              lower numbers are closer to the bottom
 342       */
 343     public void setLayer(Component c, int layer)  {
 344         setLayer(c, layer, -1);
 345     }
 346 
 347     /** Sets the layer attribute for the specified component and
 348       * also sets its position within that layer.
 349       *
 350       * @param c         the Component to set the layer for
 351       * @param layer     an int specifying the layer to set, where
 352       *                  lower numbers are closer to the bottom
 353       * @param position  an int specifying the position within the
 354       *                  layer, where 0 is the topmost position and -1
 355       *                  is the bottommost position
 356       */
 357     public void setLayer(Component c, int layer, int position)  {
 358         Integer layerObj;
 359         layerObj = getObjectForLayer(layer);
 360 
 361         if(layer == getLayer(c) && position == getPosition(c)) {
 362                 repaint(c.getBounds());
 363             return;
 364         }
 365 
 366         /// MAKE SURE THIS AND putLayer(JComponent c, int layer) are SYNCED
 367         if(c instanceof JComponent)
 368             ((JComponent)c).putClientProperty(LAYER_PROPERTY, layerObj);
 369         else
 370             getComponentToLayer().put(c, layerObj);
 371 
 372         if(c.getParent() == null || c.getParent() != this) {
 373             repaint(c.getBounds());
 374             return;
 375         }
 376 
 377         int index = insertIndexForLayer(c, layer, position);
 378 
 379         setComponentZOrder(c, index);
 380         repaint(c.getBounds());
 381     }
 382 
 383     /**
 384      * Returns the layer attribute for the specified Component.
 385      *
 386      * @param c  the Component to check
 387      * @return an int specifying the component's current layer
 388      */
 389     public int getLayer(Component c) {
 390         Integer i;
 391         if(c instanceof JComponent)
 392             i = (Integer)((JComponent)c).getClientProperty(LAYER_PROPERTY);
 393         else
 394             i = getComponentToLayer().get(c);
 395 
 396         if(i == null)
 397             return DEFAULT_LAYER.intValue();
 398         return i.intValue();
 399     }
 400 
 401     /**
 402      * Returns the index of the specified Component.
 403      * This is the absolute index, ignoring layers.
 404      * Index numbers, like position numbers, have the topmost component
 405      * at index zero. Larger numbers are closer to the bottom.
 406      *
 407      * @param c  the Component to check
 408      * @return an int specifying the component's index
 409      */
 410     public int getIndexOf(Component c) {
 411         int i, count;
 412 
 413         count = getComponentCount();
 414         for(i = 0; i < count; i++) {
 415             if(c == getComponent(i))
 416                 return i;
 417         }
 418         return -1;
 419     }
 420     /**
 421      * Moves the component to the top of the components in its current layer
 422      * (position 0).
 423      *
 424      * @param c the Component to move
 425      * @see #setPosition(Component, int)
 426      */
 427     public void moveToFront(Component c) {
 428         setPosition(c, 0);
 429     }
 430 
 431     /**
 432      * Moves the component to the bottom of the components in its current layer
 433      * (position -1).
 434      *
 435      * @param c the Component to move
 436      * @see #setPosition(Component, int)
 437      */
 438     public void moveToBack(Component c) {
 439         setPosition(c, -1);
 440     }
 441 
 442     /**
 443      * Moves the component to <code>position</code> within its current layer,
 444      * where 0 is the topmost position within the layer and -1 is the bottommost
 445      * position.
 446      * <p>
 447      * <b>Note:</b> Position numbering is defined by java.awt.Container, and
 448      * is the opposite of layer numbering. Lower position numbers are closer
 449      * to the top (0 is topmost), and higher position numbers are closer to
 450      * the bottom.
 451      *
 452      * @param c         the Component to move
 453      * @param position  an int in the range -1..N-1, where N is the number of
 454      *                  components in the component's current layer
 455      */
 456     public void setPosition(Component c, int position) {
 457         setLayer(c, getLayer(c), position);
 458     }
 459 
 460     /**
 461      * Get the relative position of the component within its layer.
 462      *
 463      * @param c  the Component to check
 464      * @return an int giving the component's position, where 0 is the
 465      *         topmost position and the highest index value = the count
 466      *         count of components at that layer, minus 1
 467      *
 468      * @see #getComponentCountInLayer
 469      */
 470     public int getPosition(Component c) {
 471         int i, startLayer, curLayer, startLocation, pos = 0;
 472 
 473         getComponentCount();
 474         startLocation = getIndexOf(c);
 475 
 476         if(startLocation == -1)
 477             return -1;
 478 
 479         startLayer = getLayer(c);
 480         for(i = startLocation - 1; i >= 0; i--) {
 481             curLayer = getLayer(getComponent(i));
 482             if(curLayer == startLayer)
 483                 pos++;
 484             else
 485                 return pos;
 486         }
 487         return pos;
 488     }
 489 
 490     /** Returns the highest layer value from all current children.
 491       * Returns 0 if there are no children.
 492       *
 493       * @return an int indicating the layer of the topmost component in the
 494       *         pane, or zero if there are no children
 495       */
 496     public int highestLayer() {
 497         if(getComponentCount() > 0)
 498             return getLayer(getComponent(0));
 499         return 0;
 500     }
 501 
 502     /** Returns the lowest layer value from all current children.
 503       * Returns 0 if there are no children.
 504       *
 505       * @return an int indicating the layer of the bottommost component in the
 506       *         pane, or zero if there are no children
 507       */
 508     public int lowestLayer() {
 509         int count = getComponentCount();
 510         if(count > 0)
 511             return getLayer(getComponent(count-1));
 512         return 0;
 513     }
 514 
 515     /**
 516      * Returns the number of children currently in the specified layer.
 517      *
 518      * @param layer  an int specifying the layer to check
 519      * @return an int specifying the number of components in that layer
 520      */
 521     public int getComponentCountInLayer(int layer) {
 522         int i, count, curLayer;
 523         int layerCount = 0;
 524 
 525         count = getComponentCount();
 526         for(i = 0; i < count; i++) {
 527             curLayer = getLayer(getComponent(i));
 528             if(curLayer == layer) {
 529                 layerCount++;
 530             /// Short circut the counting when we have them all
 531             } else if(layerCount > 0 || curLayer < layer) {
 532                 break;
 533             }
 534         }
 535 
 536         return layerCount;
 537     }
 538 
 539     /**
 540      * Returns an array of the components in the specified layer.
 541      *
 542      * @param layer  an int specifying the layer to check
 543      * @return an array of Components contained in that layer
 544      */
 545     public Component[] getComponentsInLayer(int layer) {
 546         int i, count, curLayer;
 547         int layerCount = 0;
 548         Component[] results;
 549 
 550         results = new Component[getComponentCountInLayer(layer)];
 551         count = getComponentCount();
 552         for(i = 0; i < count; i++) {
 553             curLayer = getLayer(getComponent(i));
 554             if(curLayer == layer) {
 555                 results[layerCount++] = getComponent(i);
 556             /// Short circut the counting when we have them all
 557             } else if(layerCount > 0 || curLayer < layer) {
 558                 break;
 559             }
 560         }
 561 
 562         return results;
 563     }
 564 
 565     /**
 566      * Paints this JLayeredPane within the specified graphics context.
 567      *
 568      * @param g  the Graphics context within which to paint
 569      */
 570     public void paint(Graphics g) {
 571         if(isOpaque()) {
 572             Rectangle r = g.getClipBounds();
 573             Color c = getBackground();
 574             if(c == null)
 575                 c = Color.lightGray;
 576             g.setColor(c);
 577             if (r != null) {
 578                 g.fillRect(r.x, r.y, r.width, r.height);
 579             }
 580             else {
 581                 g.fillRect(0, 0, getWidth(), getHeight());
 582             }
 583         }
 584         super.paint(g);
 585     }
 586 
 587 //////////////////////////////////////////////////////////////////////////////
 588 //// Implementation Details
 589 //////////////////////////////////////////////////////////////////////////////
 590 
 591     /**
 592      * Returns the hashtable that maps components to layers.
 593      *
 594      * @return the Hashtable used to map components to their layers
 595      */
 596     protected Hashtable<Component,Integer> getComponentToLayer() {
 597         if(componentToLayer == null)
 598             componentToLayer = new Hashtable<Component,Integer>(4);
 599         return componentToLayer;
 600     }
 601 
 602     /**
 603      * Returns the Integer object associated with a specified layer.
 604      *
 605      * @param layer an int specifying the layer
 606      * @return an Integer object for that layer
 607      */
 608     protected Integer getObjectForLayer(int layer) {
 609         switch(layer) {
 610         case 0:
 611             return DEFAULT_LAYER;
 612         case 100:
 613             return PALETTE_LAYER;
 614         case 200:
 615             return MODAL_LAYER;
 616         case 300:
 617             return POPUP_LAYER;
 618         case 400:
 619             return DRAG_LAYER;
 620         default:
 621             return layer;
 622         }
 623     }
 624 
 625     /**
 626      * Primitive method that determines the proper location to
 627      * insert a new child based on layer and position requests.
 628      *
 629      * @param layer     an int specifying the layer
 630      * @param position  an int specifying the position within the layer
 631      * @return an int giving the (absolute) insertion-index
 632      *
 633      * @see #getIndexOf
 634      */
 635     protected int insertIndexForLayer(int layer, int position) {
 636         return insertIndexForLayer(null, layer, position);
 637     }
 638 
 639     /**
 640      * This method is an extended version of insertIndexForLayer()
 641      * to support setLayer which uses Container.setZOrder which does
 642      * not remove the component from the containment hierarchy though
 643      * we need to ignore it when calculating the insertion index.
 644      *
 645      * @param comp      component to ignore when determining index
 646      * @param layer     an int specifying the layer
 647      * @param position  an int specifying the position within the layer
 648      * @return an int giving the (absolute) insertion-index
 649      *
 650      * @see #getIndexOf
 651      */
 652     private int insertIndexForLayer(Component comp, int layer, int position) {
 653         int i, count, curLayer;
 654         int layerStart = -1;
 655         int layerEnd = -1;
 656         int componentCount = getComponentCount();
 657 
 658         ArrayList<Component> compList =
 659             new ArrayList<Component>(componentCount);
 660         for (int index = 0; index < componentCount; index++) {
 661             if (getComponent(index) != comp) {
 662                 compList.add(getComponent(index));
 663             }
 664         }
 665 
 666         count = compList.size();
 667         for (i = 0; i < count; i++) {
 668             curLayer = getLayer(compList.get(i));
 669             if (layerStart == -1 && curLayer == layer) {
 670                 layerStart = i;
 671             }
 672             if (curLayer < layer) {
 673                 if (i == 0) {
 674                     // layer is greater than any current layer
 675                     // [ ASSERT(layer > highestLayer()) ]
 676                     layerStart = 0;
 677                     layerEnd = 0;
 678                 } else {
 679                     layerEnd = i;
 680                 }
 681                 break;
 682             }
 683         }
 684 
 685         // layer requested is lower than any current layer
 686         // [ ASSERT(layer < lowestLayer()) ]
 687         // put it on the bottom of the stack
 688         if (layerStart == -1 && layerEnd == -1)
 689             return count;
 690 
 691         // In the case of a single layer entry handle the degenerative cases
 692         if (layerStart != -1 && layerEnd == -1)
 693             layerEnd = count;
 694 
 695         if (layerEnd != -1 && layerStart == -1)
 696             layerStart = layerEnd;
 697 
 698         // If we are adding to the bottom, return the last element
 699         if (position == -1)
 700             return layerEnd;
 701 
 702         // Otherwise make sure the requested position falls in the
 703         // proper range
 704         if (position > -1 && layerStart + position <= layerEnd)
 705             return layerStart + position;
 706 
 707         // Otherwise return the end of the layer
 708         return layerEnd;
 709     }
 710 
 711     /**
 712      * Returns a string representation of this JLayeredPane. This method
 713      * is intended to be used only for debugging purposes, and the
 714      * content and format of the returned string may vary between
 715      * implementations. The returned string may be empty but may not
 716      * be <code>null</code>.
 717      *
 718      * @return  a string representation of this JLayeredPane.
 719      */
 720     protected String paramString() {
 721         String optimizedDrawingPossibleString = (optimizedDrawingPossible ?
 722                                                  "true" : "false");
 723 
 724         return super.paramString() +
 725         ",optimizedDrawingPossible=" + optimizedDrawingPossibleString;
 726     }
 727 
 728 /////////////////
 729 // Accessibility support
 730 ////////////////
 731 
 732     /**
 733      * Gets the AccessibleContext associated with this JLayeredPane.
 734      * For layered panes, the AccessibleContext takes the form of an
 735      * AccessibleJLayeredPane.
 736      * A new AccessibleJLayeredPane instance is created if necessary.
 737      *
 738      * @return an AccessibleJLayeredPane that serves as the
 739      *         AccessibleContext of this JLayeredPane
 740      */
 741     public AccessibleContext getAccessibleContext() {
 742         if (accessibleContext == null) {
 743             accessibleContext = new AccessibleJLayeredPane();
 744         }
 745         return accessibleContext;
 746     }
 747 
 748     /**
 749      * This class implements accessibility support for the
 750      * <code>JLayeredPane</code> class.  It provides an implementation of the
 751      * Java Accessibility API appropriate to layered pane user-interface
 752      * elements.
 753      * <p>
 754      * <strong>Warning:</strong>
 755      * Serialized objects of this class will not be compatible with
 756      * future Swing releases. The current serialization support is
 757      * appropriate for short term storage or RMI between applications running
 758      * the same version of Swing.  As of 1.4, support for long term storage
 759      * of all JavaBeans&trade;
 760      * has been added to the <code>java.beans</code> package.
 761      * Please see {@link java.beans.XMLEncoder}.
 762      */
 763     @SuppressWarnings("serial")
 764     protected class AccessibleJLayeredPane extends AccessibleJComponent {
 765 
 766         /**
 767          * Get the role of this object.
 768          *
 769          * @return an instance of AccessibleRole describing the role of the
 770          * object
 771          * @see AccessibleRole
 772          */
 773         public AccessibleRole getAccessibleRole() {
 774             return AccessibleRole.LAYERED_PANE;
 775         }
 776     }
 777 }