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 = new Integer(0);
 163     /** Convenience object defining the Palette layer. Equivalent to new Integer(100).*/
 164     public final static Integer PALETTE_LAYER = new Integer(100);
 165     /** Convenience object defining the Modal layer. Equivalent to new Integer(200).*/
 166     public final static Integer MODAL_LAYER = new Integer(200);
 167     /** Convenience object defining the Popup layer. Equivalent to new Integer(300).*/
 168     public final static Integer POPUP_LAYER = new Integer(300);
 169     /** Convenience object defining the Drag layer. Equivalent to new Integer(400).*/
 170     public final static Integer DRAG_LAYER = new Integer(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         Integer layerObj;
 298 
 299         layerObj = layer;
 300         c.putClientProperty(LAYER_PROPERTY, layerObj);
 301     }
 302 
 303     /** Gets the layer property for a JComponent, it
 304       * does not cause any side effects like setLayer(). (painting, add/remove, etc)
 305       * Normally you should use the instance method getLayer().
 306       *
 307       * @param c  the JComponent to check
 308       * @return   an int specifying the component's layer
 309       */
 310     public static int getLayer(JComponent c) {
 311         Integer i;
 312         if((i = (Integer)c.getClientProperty(LAYER_PROPERTY)) != null)
 313             return i.intValue();
 314         return DEFAULT_LAYER.intValue();
 315     }
 316 
 317     /** Convenience method that returns the first JLayeredPane which
 318       * contains the specified component. Note that all JFrames have a
 319       * JLayeredPane at their root, so any component in a JFrame will
 320       * have a JLayeredPane parent.
 321       *
 322       * @param c the Component to check
 323       * @return the JLayeredPane that contains the component, or
 324       *         null if no JLayeredPane is found in the component
 325       *         hierarchy
 326       * @see JFrame
 327       * @see JRootPane
 328       */
 329     public static JLayeredPane getLayeredPaneAbove(Component c) {
 330         if(c == null) return null;
 331 
 332         Component parent = c.getParent();
 333         while(parent != null && !(parent instanceof JLayeredPane))
 334             parent = parent.getParent();
 335         return (JLayeredPane)parent;
 336     }
 337 
 338     /** Sets the layer attribute on the specified component,
 339       * making it the bottommost component in that layer.
 340       * Should be called before adding to parent.
 341       *
 342       * @param c     the Component to set the layer for
 343       * @param layer an int specifying the layer to set, where
 344       *              lower numbers are closer to the bottom
 345       */
 346     public void setLayer(Component c, int layer)  {
 347         setLayer(c, layer, -1);
 348     }
 349 
 350     /** Sets the layer attribute for the specified component and
 351       * also sets its position within that layer.
 352       *
 353       * @param c         the Component to set the layer for
 354       * @param layer     an int specifying the layer to set, where
 355       *                  lower numbers are closer to the bottom
 356       * @param position  an int specifying the position within the
 357       *                  layer, where 0 is the topmost position and -1
 358       *                  is the bottommost position
 359       */
 360     public void setLayer(Component c, int layer, int position)  {
 361         Integer layerObj;
 362         layerObj = getObjectForLayer(layer);
 363 
 364         if(layer == getLayer(c) && position == getPosition(c)) {
 365                 repaint(c.getBounds());
 366             return;
 367         }
 368 
 369         /// MAKE SURE THIS AND putLayer(JComponent c, int layer) are SYNCED
 370         if(c instanceof JComponent)
 371             ((JComponent)c).putClientProperty(LAYER_PROPERTY, layerObj);
 372         else
 373             getComponentToLayer().put(c, layerObj);
 374 
 375         if(c.getParent() == null || c.getParent() != this) {
 376             repaint(c.getBounds());
 377             return;
 378         }
 379 
 380         int index = insertIndexForLayer(c, layer, position);
 381 
 382         setComponentZOrder(c, index);
 383         repaint(c.getBounds());
 384     }
 385 
 386     /**
 387      * Returns the layer attribute for the specified Component.
 388      *
 389      * @param c  the Component to check
 390      * @return an int specifying the component's current layer
 391      */
 392     public int getLayer(Component c) {
 393         Integer i;
 394         if(c instanceof JComponent)
 395             i = (Integer)((JComponent)c).getClientProperty(LAYER_PROPERTY);
 396         else
 397             i = getComponentToLayer().get(c);
 398 
 399         if(i == null)
 400             return DEFAULT_LAYER.intValue();
 401         return i.intValue();
 402     }
 403 
 404     /**
 405      * Returns the index of the specified Component.
 406      * This is the absolute index, ignoring layers.
 407      * Index numbers, like position numbers, have the topmost component
 408      * at index zero. Larger numbers are closer to the bottom.
 409      *
 410      * @param c  the Component to check
 411      * @return an int specifying the component's index
 412      */
 413     public int getIndexOf(Component c) {
 414         int i, count;
 415 
 416         count = getComponentCount();
 417         for(i = 0; i < count; i++) {
 418             if(c == getComponent(i))
 419                 return i;
 420         }
 421         return -1;
 422     }
 423     /**
 424      * Moves the component to the top of the components in its current layer
 425      * (position 0).
 426      *
 427      * @param c the Component to move
 428      * @see #setPosition(Component, int)
 429      */
 430     public void moveToFront(Component c) {
 431         setPosition(c, 0);
 432     }
 433 
 434     /**
 435      * Moves the component to the bottom of the components in its current layer
 436      * (position -1).
 437      *
 438      * @param c the Component to move
 439      * @see #setPosition(Component, int)
 440      */
 441     public void moveToBack(Component c) {
 442         setPosition(c, -1);
 443     }
 444 
 445     /**
 446      * Moves the component to <code>position</code> within its current layer,
 447      * where 0 is the topmost position within the layer and -1 is the bottommost
 448      * position.
 449      * <p>
 450      * <b>Note:</b> Position numbering is defined by java.awt.Container, and
 451      * is the opposite of layer numbering. Lower position numbers are closer
 452      * to the top (0 is topmost), and higher position numbers are closer to
 453      * the bottom.
 454      *
 455      * @param c         the Component to move
 456      * @param position  an int in the range -1..N-1, where N is the number of
 457      *                  components in the component's current layer
 458      */
 459     public void setPosition(Component c, int position) {
 460         setLayer(c, getLayer(c), position);
 461     }
 462 
 463     /**
 464      * Get the relative position of the component within its layer.
 465      *
 466      * @param c  the Component to check
 467      * @return an int giving the component's position, where 0 is the
 468      *         topmost position and the highest index value = the count
 469      *         count of components at that layer, minus 1
 470      *
 471      * @see #getComponentCountInLayer
 472      */
 473     public int getPosition(Component c) {
 474         int i, startLayer, curLayer, startLocation, pos = 0;
 475 
 476         getComponentCount();
 477         startLocation = getIndexOf(c);
 478 
 479         if(startLocation == -1)
 480             return -1;
 481 
 482         startLayer = getLayer(c);
 483         for(i = startLocation - 1; i >= 0; i--) {
 484             curLayer = getLayer(getComponent(i));
 485             if(curLayer == startLayer)
 486                 pos++;
 487             else
 488                 return pos;
 489         }
 490         return pos;
 491     }
 492 
 493     /** Returns the highest layer value from all current children.
 494       * Returns 0 if there are no children.
 495       *
 496       * @return an int indicating the layer of the topmost component in the
 497       *         pane, or zero if there are no children
 498       */
 499     public int highestLayer() {
 500         if(getComponentCount() > 0)
 501             return getLayer(getComponent(0));
 502         return 0;
 503     }
 504 
 505     /** Returns the lowest layer value from all current children.
 506       * Returns 0 if there are no children.
 507       *
 508       * @return an int indicating the layer of the bottommost component in the
 509       *         pane, or zero if there are no children
 510       */
 511     public int lowestLayer() {
 512         int count = getComponentCount();
 513         if(count > 0)
 514             return getLayer(getComponent(count-1));
 515         return 0;
 516     }
 517 
 518     /**
 519      * Returns the number of children currently in the specified layer.
 520      *
 521      * @param layer  an int specifying the layer to check
 522      * @return an int specifying the number of components in that layer
 523      */
 524     public int getComponentCountInLayer(int layer) {
 525         int i, count, curLayer;
 526         int layerCount = 0;
 527 
 528         count = getComponentCount();
 529         for(i = 0; i < count; i++) {
 530             curLayer = getLayer(getComponent(i));
 531             if(curLayer == layer) {
 532                 layerCount++;
 533             /// Short circut the counting when we have them all
 534             } else if(layerCount > 0 || curLayer < layer) {
 535                 break;
 536             }
 537         }
 538 
 539         return layerCount;
 540     }
 541 
 542     /**
 543      * Returns an array of the components in the specified layer.
 544      *
 545      * @param layer  an int specifying the layer to check
 546      * @return an array of Components contained in that layer
 547      */
 548     public Component[] getComponentsInLayer(int layer) {
 549         int i, count, curLayer;
 550         int layerCount = 0;
 551         Component[] results;
 552 
 553         results = new Component[getComponentCountInLayer(layer)];
 554         count = getComponentCount();
 555         for(i = 0; i < count; i++) {
 556             curLayer = getLayer(getComponent(i));
 557             if(curLayer == layer) {
 558                 results[layerCount++] = getComponent(i);
 559             /// Short circut the counting when we have them all
 560             } else if(layerCount > 0 || curLayer < layer) {
 561                 break;
 562             }
 563         }
 564 
 565         return results;
 566     }
 567 
 568     /**
 569      * Paints this JLayeredPane within the specified graphics context.
 570      *
 571      * @param g  the Graphics context within which to paint
 572      */
 573     public void paint(Graphics g) {
 574         if(isOpaque()) {
 575             Rectangle r = g.getClipBounds();
 576             Color c = getBackground();
 577             if(c == null)
 578                 c = Color.lightGray;
 579             g.setColor(c);
 580             if (r != null) {
 581                 g.fillRect(r.x, r.y, r.width, r.height);
 582             }
 583             else {
 584                 g.fillRect(0, 0, getWidth(), getHeight());
 585             }
 586         }
 587         super.paint(g);
 588     }
 589 
 590 //////////////////////////////////////////////////////////////////////////////
 591 //// Implementation Details
 592 //////////////////////////////////////////////////////////////////////////////
 593 
 594     /**
 595      * Returns the hashtable that maps components to layers.
 596      *
 597      * @return the Hashtable used to map components to their layers
 598      */
 599     protected Hashtable<Component,Integer> getComponentToLayer() {
 600         if(componentToLayer == null)
 601             componentToLayer = new Hashtable<Component,Integer>(4);
 602         return componentToLayer;
 603     }
 604 
 605     /**
 606      * Returns the Integer object associated with a specified layer.
 607      *
 608      * @param layer an int specifying the layer
 609      * @return an Integer object for that layer
 610      */
 611     protected Integer getObjectForLayer(int layer) {
 612         Integer layerObj;
 613         switch(layer) {
 614         case 0:
 615             layerObj = DEFAULT_LAYER;
 616             break;
 617         case 100:
 618             layerObj = PALETTE_LAYER;
 619             break;
 620         case 200:
 621             layerObj = MODAL_LAYER;
 622             break;
 623         case 300:
 624             layerObj = POPUP_LAYER;
 625             break;
 626         case 400:
 627             layerObj = DRAG_LAYER;
 628             break;
 629         default:
 630             layerObj = layer;
 631         }
 632         return layerObj;
 633     }
 634 
 635     /**
 636      * Primitive method that determines the proper location to
 637      * insert a new child based on layer and position requests.
 638      *
 639      * @param layer     an int specifying the layer
 640      * @param position  an int specifying the position within the layer
 641      * @return an int giving the (absolute) insertion-index
 642      *
 643      * @see #getIndexOf
 644      */
 645     protected int insertIndexForLayer(int layer, int position) {
 646         return insertIndexForLayer(null, layer, position);
 647     }
 648 
 649     /**
 650      * This method is an extended version of insertIndexForLayer()
 651      * to support setLayer which uses Container.setZOrder which does
 652      * not remove the component from the containment hierarchy though
 653      * we need to ignore it when calculating the insertion index.
 654      *
 655      * @param comp      component to ignore when determining index
 656      * @param layer     an int specifying the layer
 657      * @param position  an int specifying the position within the layer
 658      * @return an int giving the (absolute) insertion-index
 659      *
 660      * @see #getIndexOf
 661      */
 662     private int insertIndexForLayer(Component comp, int layer, int position) {
 663         int i, count, curLayer;
 664         int layerStart = -1;
 665         int layerEnd = -1;
 666         int componentCount = getComponentCount();
 667 
 668         ArrayList<Component> compList =
 669             new ArrayList<Component>(componentCount);
 670         for (int index = 0; index < componentCount; index++) {
 671             if (getComponent(index) != comp) {
 672                 compList.add(getComponent(index));
 673             }
 674         }
 675 
 676         count = compList.size();
 677         for (i = 0; i < count; i++) {
 678             curLayer = getLayer(compList.get(i));
 679             if (layerStart == -1 && curLayer == layer) {
 680                 layerStart = i;
 681             }
 682             if (curLayer < layer) {
 683                 if (i == 0) {
 684                     // layer is greater than any current layer
 685                     // [ ASSERT(layer > highestLayer()) ]
 686                     layerStart = 0;
 687                     layerEnd = 0;
 688                 } else {
 689                     layerEnd = i;
 690                 }
 691                 break;
 692             }
 693         }
 694 
 695         // layer requested is lower than any current layer
 696         // [ ASSERT(layer < lowestLayer()) ]
 697         // put it on the bottom of the stack
 698         if (layerStart == -1 && layerEnd == -1)
 699             return count;
 700 
 701         // In the case of a single layer entry handle the degenerative cases
 702         if (layerStart != -1 && layerEnd == -1)
 703             layerEnd = count;
 704 
 705         if (layerEnd != -1 && layerStart == -1)
 706             layerStart = layerEnd;
 707 
 708         // If we are adding to the bottom, return the last element
 709         if (position == -1)
 710             return layerEnd;
 711 
 712         // Otherwise make sure the requested position falls in the
 713         // proper range
 714         if (position > -1 && layerStart + position <= layerEnd)
 715             return layerStart + position;
 716 
 717         // Otherwise return the end of the layer
 718         return layerEnd;
 719     }
 720 
 721     /**
 722      * Returns a string representation of this JLayeredPane. This method
 723      * is intended to be used only for debugging purposes, and the
 724      * content and format of the returned string may vary between
 725      * implementations. The returned string may be empty but may not
 726      * be <code>null</code>.
 727      *
 728      * @return  a string representation of this JLayeredPane.
 729      */
 730     protected String paramString() {
 731         String optimizedDrawingPossibleString = (optimizedDrawingPossible ?
 732                                                  "true" : "false");
 733 
 734         return super.paramString() +
 735         ",optimizedDrawingPossible=" + optimizedDrawingPossibleString;
 736     }
 737 
 738 /////////////////
 739 // Accessibility support
 740 ////////////////
 741 
 742     /**
 743      * Gets the AccessibleContext associated with this JLayeredPane.
 744      * For layered panes, the AccessibleContext takes the form of an
 745      * AccessibleJLayeredPane.
 746      * A new AccessibleJLayeredPane instance is created if necessary.
 747      *
 748      * @return an AccessibleJLayeredPane that serves as the
 749      *         AccessibleContext of this JLayeredPane
 750      */
 751     public AccessibleContext getAccessibleContext() {
 752         if (accessibleContext == null) {
 753             accessibleContext = new AccessibleJLayeredPane();
 754         }
 755         return accessibleContext;
 756     }
 757 
 758     /**
 759      * This class implements accessibility support for the
 760      * <code>JLayeredPane</code> class.  It provides an implementation of the
 761      * Java Accessibility API appropriate to layered pane user-interface
 762      * elements.
 763      * <p>
 764      * <strong>Warning:</strong>
 765      * Serialized objects of this class will not be compatible with
 766      * future Swing releases. The current serialization support is
 767      * appropriate for short term storage or RMI between applications running
 768      * the same version of Swing.  As of 1.4, support for long term storage
 769      * of all JavaBeans&trade;
 770      * has been added to the <code>java.beans</code> package.
 771      * Please see {@link java.beans.XMLEncoder}.
 772      */
 773     @SuppressWarnings("serial")
 774     protected class AccessibleJLayeredPane extends AccessibleJComponent {
 775 
 776         /**
 777          * Get the role of this object.
 778          *
 779          * @return an instance of AccessibleRole describing the role of the
 780          * object
 781          * @see AccessibleRole
 782          */
 783         public AccessibleRole getAccessibleRole() {
 784             return AccessibleRole.LAYERED_PANE;
 785         }
 786     }
 787 }