1 /*
   2  * Copyright (c) 1997, 2014, 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 
  26 package javax.swing;
  27 
  28 import java.awt.*;
  29 import java.awt.event.*;
  30 
  31 import java.util.Vector;
  32 import java.util.Locale;
  33 import java.util.ArrayList;
  34 import java.util.Collections;
  35 import java.util.List;
  36 
  37 import java.beans.PropertyChangeEvent;
  38 import java.beans.PropertyChangeListener;
  39 import java.beans.Transient;
  40 
  41 import javax.swing.event.*;
  42 import javax.accessibility.*;
  43 import javax.swing.plaf.*;
  44 import javax.swing.text.Position;
  45 
  46 import java.io.ObjectOutputStream;
  47 import java.io.ObjectInputStream;
  48 import java.io.IOException;
  49 import java.io.Serializable;
  50 
  51 import sun.swing.SwingUtilities2;
  52 import sun.swing.SwingUtilities2.Section;
  53 import static sun.swing.SwingUtilities2.Section.*;
  54 
  55 
  56 /**
  57  * A component that displays a list of objects and allows the user to select
  58  * one or more items. A separate model, {@code ListModel}, maintains the
  59  * contents of the list.
  60  * <p>
  61  * It's easy to display an array or Vector of objects, using the {@code JList}
  62  * constructor that automatically builds a read-only {@code ListModel} instance
  63  * for you:
  64  * <pre>
  65  * {@code
  66  * // Create a JList that displays strings from an array
  67  *
  68  * String[] data = {"one", "two", "three", "four"};
  69  * JList<String> myList = new JList<String>(data);
  70  *
  71  * // Create a JList that displays the superclasses of JList.class, by
  72  * // creating it with a Vector populated with this data
  73  *
  74  * Vector<Class<?>> superClasses = new Vector<Class<?>>();
  75  * Class<JList> rootClass = javax.swing.JList.class;
  76  * for(Class<?> cls = rootClass; cls != null; cls = cls.getSuperclass()) {
  77  *     superClasses.addElement(cls);
  78  * }
  79  * JList<Class<?>> myList = new JList<Class<?>>(superClasses);
  80  *
  81  * // The automatically created model is stored in JList's "model"
  82  * // property, which you can retrieve
  83  *
  84  * ListModel<Class<?>> model = myList.getModel();
  85  * for(int i = 0; i < model.getSize(); i++) {
  86  *     System.out.println(model.getElementAt(i));
  87  * }
  88  * }
  89  * </pre>
  90  * <p>
  91  * A {@code ListModel} can be supplied directly to a {@code JList} by way of a
  92  * constructor or the {@code setModel} method. The contents need not be static -
  93  * the number of items, and the values of items can change over time. A correct
  94  * {@code ListModel} implementation notifies the set of
  95  * {@code javax.swing.event.ListDataListener}s that have been added to it, each
  96  * time a change occurs. These changes are characterized by a
  97  * {@code javax.swing.event.ListDataEvent}, which identifies the range of list
  98  * indices that have been modified, added, or removed. {@code JList}'s
  99  * {@code ListUI} is responsible for keeping the visual representation up to
 100  * date with changes, by listening to the model.
 101  * <p>
 102  * Simple, dynamic-content, {@code JList} applications can use the
 103  * {@code DefaultListModel} class to maintain list elements. This class
 104  * implements the {@code ListModel} interface and also provides a
 105  * <code>java.util.Vector</code>-like API. Applications that need a more
 106  * custom <code>ListModel</code> implementation may instead wish to subclass
 107  * {@code AbstractListModel}, which provides basic support for managing and
 108  * notifying listeners. For example, a read-only implementation of
 109  * {@code AbstractListModel}:
 110  * <pre>
 111  * {@code
 112  * // This list model has about 2^16 elements.  Enjoy scrolling.
 113  *
 114  * ListModel<String> bigData = new AbstractListModel<String>() {
 115  *     public int getSize() { return Short.MAX_VALUE; }
 116  *     public String getElementAt(int index) { return "Index " + index; }
 117  * };
 118  * }
 119  * </pre>
 120  * <p>
 121  * The selection state of a {@code JList} is managed by another separate
 122  * model, an instance of {@code ListSelectionModel}. {@code JList} is
 123  * initialized with a selection model on construction, and also contains
 124  * methods to query or set this selection model. Additionally, {@code JList}
 125  * provides convenient methods for easily managing the selection. These methods,
 126  * such as {@code setSelectedIndex} and {@code getSelectedValue}, are cover
 127  * methods that take care of the details of interacting with the selection
 128  * model. By default, {@code JList}'s selection model is configured to allow any
 129  * combination of items to be selected at a time; selection mode
 130  * {@code MULTIPLE_INTERVAL_SELECTION}. The selection mode can be changed
 131  * on the selection model directly, or via {@code JList}'s cover method.
 132  * Responsibility for updating the selection model in response to user gestures
 133  * lies with the list's {@code ListUI}.
 134  * <p>
 135  * A correct {@code ListSelectionModel} implementation notifies the set of
 136  * {@code javax.swing.event.ListSelectionListener}s that have been added to it
 137  * each time a change to the selection occurs. These changes are characterized
 138  * by a {@code javax.swing.event.ListSelectionEvent}, which identifies the range
 139  * of the selection change.
 140  * <p>
 141  * The preferred way to listen for changes in list selection is to add
 142  * {@code ListSelectionListener}s directly to the {@code JList}. {@code JList}
 143  * then takes care of listening to the the selection model and notifying your
 144  * listeners of change.
 145  * <p>
 146  * Responsibility for listening to selection changes in order to keep the list's
 147  * visual representation up to date lies with the list's {@code ListUI}.
 148  * <p>
 149  * <a name="renderer"></a>
 150  * Painting of cells in a {@code JList} is handled by a delegate called a
 151  * cell renderer, installed on the list as the {@code cellRenderer} property.
 152  * The renderer provides a {@code java.awt.Component} that is used
 153  * like a "rubber stamp" to paint the cells. Each time a cell needs to be
 154  * painted, the list's {@code ListUI} asks the cell renderer for the component,
 155  * moves it into place, and has it paint the contents of the cell by way of its
 156  * {@code paint} method. A default cell renderer, which uses a {@code JLabel}
 157  * component to render, is installed by the lists's {@code ListUI}. You can
 158  * substitute your own renderer using code like this:
 159  * <pre>
 160  * {@code
 161  *  // Display an icon and a string for each object in the list.
 162  *
 163  * class MyCellRenderer extends JLabel implements ListCellRenderer<Object> {
 164  *     final static ImageIcon longIcon = new ImageIcon("long.gif");
 165  *     final static ImageIcon shortIcon = new ImageIcon("short.gif");
 166  *
 167  *     // This is the only method defined by ListCellRenderer.
 168  *     // We just reconfigure the JLabel each time we're called.
 169  *
 170  *     public Component getListCellRendererComponent(
 171  *       JList<?> list,           // the list
 172  *       Object value,            // value to display
 173  *       int index,               // cell index
 174  *       boolean isSelected,      // is the cell selected
 175  *       boolean cellHasFocus)    // does the cell have focus
 176  *     {
 177  *         String s = value.toString();
 178  *         setText(s);
 179  *         setIcon((s.length() > 10) ? longIcon : shortIcon);
 180  *         if (isSelected) {
 181  *             setBackground(list.getSelectionBackground());
 182  *             setForeground(list.getSelectionForeground());
 183  *         } else {
 184  *             setBackground(list.getBackground());
 185  *             setForeground(list.getForeground());
 186  *         }
 187  *         setEnabled(list.isEnabled());
 188  *         setFont(list.getFont());
 189  *         setOpaque(true);
 190  *         return this;
 191  *     }
 192  * }
 193  *
 194  * myList.setCellRenderer(new MyCellRenderer());
 195  * }
 196  * </pre>
 197  * <p>
 198  * Another job for the cell renderer is in helping to determine sizing
 199  * information for the list. By default, the list's {@code ListUI} determines
 200  * the size of cells by asking the cell renderer for its preferred
 201  * size for each list item. This can be expensive for large lists of items.
 202  * To avoid these calculations, you can set a {@code fixedCellWidth} and
 203  * {@code fixedCellHeight} on the list, or have these values calculated
 204  * automatically based on a single prototype value:
 205  * <a name="prototype_example"></a>
 206  * <pre>
 207  * {@code
 208  * JList<String> bigDataList = new JList<String>(bigData);
 209  *
 210  * // We don't want the JList implementation to compute the width
 211  * // or height of all of the list cells, so we give it a string
 212  * // that's as big as we'll need for any cell.  It uses this to
 213  * // compute values for the fixedCellWidth and fixedCellHeight
 214  * // properties.
 215  *
 216  * bigDataList.setPrototypeCellValue("Index 1234567890");
 217  * }
 218  * </pre>
 219  * <p>
 220  * {@code JList} doesn't implement scrolling directly. To create a list that
 221  * scrolls, make it the viewport view of a {@code JScrollPane}. For example:
 222  * <pre>
 223  * JScrollPane scrollPane = new JScrollPane(myList);
 224  *
 225  * // Or in two steps:
 226  * JScrollPane scrollPane = new JScrollPane();
 227  * scrollPane.getViewport().setView(myList);
 228  * </pre>
 229  * <p>
 230  * {@code JList} doesn't provide any special handling of double or triple
 231  * (or N) mouse clicks, but it's easy to add a {@code MouseListener} if you
 232  * wish to take action on these events. Use the {@code locationToIndex}
 233  * method to determine what cell was clicked. For example:
 234  * <pre>
 235  * MouseListener mouseListener = new MouseAdapter() {
 236  *     public void mouseClicked(MouseEvent e) {
 237  *         if (e.getClickCount() == 2) {
 238  *             int index = list.locationToIndex(e.getPoint());
 239  *             System.out.println("Double clicked on Item " + index);
 240  *          }
 241  *     }
 242  * };
 243  * list.addMouseListener(mouseListener);
 244  * </pre>
 245  * <p>
 246  * <strong>Warning:</strong> Swing is not thread safe. For more
 247  * information see <a
 248  * href="package-summary.html#threading">Swing's Threading
 249  * Policy</a>.
 250  * <p>
 251  * <strong>Warning:</strong>
 252  * Serialized objects of this class will not be compatible with
 253  * future Swing releases. The current serialization support is
 254  * appropriate for short term storage or RMI between applications running
 255  * the same version of Swing.  As of 1.4, support for long term storage
 256  * of all JavaBeans&trade;
 257  * has been added to the <code>java.beans</code> package.
 258  * Please see {@link java.beans.XMLEncoder}.
 259  * <p>
 260  * See <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/list.html">How to Use Lists</a>
 261  * in <a href="http://docs.oracle.com/javase/tutorial/"><em>The Java Tutorial</em></a>
 262  * for further documentation.
 263  *
 264  * @see ListModel
 265  * @see AbstractListModel
 266  * @see DefaultListModel
 267  * @see ListSelectionModel
 268  * @see DefaultListSelectionModel
 269  * @see ListCellRenderer
 270  * @see DefaultListCellRenderer
 271  *
 272  * @param <E> the type of the elements of this list
 273  *
 274  * @beaninfo
 275  *   attribute: isContainer false
 276  * description: A component which allows for the selection of one or more objects from a list.
 277  *
 278  * @author Hans Muller
 279  */
 280 @SuppressWarnings("serial") // Same-version serialization only
 281 public class JList<E> extends JComponent implements Scrollable, Accessible
 282 {
 283     /**
 284      * @see #getUIClassID
 285      * @see #readObject
 286      */
 287     private static final String uiClassID = "ListUI";
 288 
 289     /**
 290      * Indicates a vertical layout of cells, in a single column;
 291      * the default layout.
 292      * @see #setLayoutOrientation
 293      * @since 1.4
 294      */
 295     public static final int VERTICAL = 0;
 296 
 297     /**
 298      * Indicates a "newspaper style" layout with cells flowing vertically
 299      * then horizontally.
 300      * @see #setLayoutOrientation
 301      * @since 1.4
 302      */
 303     public static final int VERTICAL_WRAP = 1;
 304 
 305     /**
 306      * Indicates a "newspaper style" layout with cells flowing horizontally
 307      * then vertically.
 308      * @see #setLayoutOrientation
 309      * @since 1.4
 310      */
 311     public static final int HORIZONTAL_WRAP = 2;
 312 
 313     private int fixedCellWidth = -1;
 314     private int fixedCellHeight = -1;
 315     private int horizontalScrollIncrement = -1;
 316     private E prototypeCellValue;
 317     private int visibleRowCount = 8;
 318     private Color selectionForeground;
 319     private Color selectionBackground;
 320     private boolean dragEnabled;
 321 
 322     private ListSelectionModel selectionModel;
 323     private ListModel<E> dataModel;
 324     private ListCellRenderer<? super E> cellRenderer;
 325     private ListSelectionListener selectionListener;
 326 
 327     /**
 328      * How to lay out the cells; defaults to <code>VERTICAL</code>.
 329      */
 330     private int layoutOrientation;
 331 
 332     /**
 333      * The drop mode for this component.
 334      */
 335     private DropMode dropMode = DropMode.USE_SELECTION;
 336 
 337     /**
 338      * The drop location.
 339      */
 340     private transient DropLocation dropLocation;
 341 
 342     /**
 343      * A subclass of <code>TransferHandler.DropLocation</code> representing
 344      * a drop location for a <code>JList</code>.
 345      *
 346      * @see #getDropLocation
 347      * @since 1.6
 348      */
 349     public static final class DropLocation extends TransferHandler.DropLocation {
 350         private final int index;
 351         private final boolean isInsert;
 352 
 353         private DropLocation(Point p, int index, boolean isInsert) {
 354             super(p);
 355             this.index = index;
 356             this.isInsert = isInsert;
 357         }
 358 
 359         /**
 360          * Returns the index where dropped data should be placed in the
 361          * list. Interpretation of the value depends on the drop mode set on
 362          * the associated component. If the drop mode is either
 363          * <code>DropMode.USE_SELECTION</code> or <code>DropMode.ON</code>,
 364          * the return value is an index of a row in the list. If the drop mode is
 365          * <code>DropMode.INSERT</code>, the return value refers to the index
 366          * where the data should be inserted. If the drop mode is
 367          * <code>DropMode.ON_OR_INSERT</code>, the value of
 368          * <code>isInsert()</code> indicates whether the index is an index
 369          * of a row, or an insert index.
 370          * <p>
 371          * <code>-1</code> indicates that the drop occurred over empty space,
 372          * and no index could be calculated.
 373          *
 374          * @return the drop index
 375          */
 376         public int getIndex() {
 377             return index;
 378         }
 379 
 380         /**
 381          * Returns whether or not this location represents an insert
 382          * location.
 383          *
 384          * @return whether or not this is an insert location
 385          */
 386         public boolean isInsert() {
 387             return isInsert;
 388         }
 389 
 390         /**
 391          * Returns a string representation of this drop location.
 392          * This method is intended to be used for debugging purposes,
 393          * and the content and format of the returned string may vary
 394          * between implementations.
 395          *
 396          * @return a string representation of this drop location
 397          */
 398         public String toString() {
 399             return getClass().getName()
 400                    + "[dropPoint=" + getDropPoint() + ","
 401                    + "index=" + index + ","
 402                    + "insert=" + isInsert + "]";
 403         }
 404     }
 405 
 406     /**
 407      * Constructs a {@code JList} that displays elements from the specified,
 408      * {@code non-null}, model. All {@code JList} constructors delegate to
 409      * this one.
 410      * <p>
 411      * This constructor registers the list with the {@code ToolTipManager},
 412      * allowing for tooltips to be provided by the cell renderers.
 413      *
 414      * @param dataModel the model for the list
 415      * @exception IllegalArgumentException if the model is {@code null}
 416      */
 417     public JList(ListModel<E> dataModel)
 418     {
 419         if (dataModel == null) {
 420             throw new IllegalArgumentException("dataModel must be non null");
 421         }
 422 
 423         // Register with the ToolTipManager so that tooltips from the
 424         // renderer show through.
 425         ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
 426         toolTipManager.registerComponent(this);
 427 
 428         layoutOrientation = VERTICAL;
 429 
 430         this.dataModel = dataModel;
 431         selectionModel = createSelectionModel();
 432         setAutoscrolls(true);
 433         setOpaque(true);
 434         updateUI();
 435     }
 436 
 437 
 438     /**
 439      * Constructs a <code>JList</code> that displays the elements in
 440      * the specified array. This constructor creates a read-only model
 441      * for the given array, and then delegates to the constructor that
 442      * takes a {@code ListModel}.
 443      * <p>
 444      * Attempts to pass a {@code null} value to this method results in
 445      * undefined behavior and, most likely, exceptions. The created model
 446      * references the given array directly. Attempts to modify the array
 447      * after constructing the list results in undefined behavior.
 448      *
 449      * @param  listData  the array of Objects to be loaded into the data model,
 450      *                   {@code non-null}
 451      */
 452     public JList(final E[] listData)
 453     {
 454         this (
 455             new AbstractListModel<E>() {
 456                 public int getSize() { return listData.length; }
 457                 public E getElementAt(int i) { return listData[i]; }
 458             }
 459         );
 460     }
 461 
 462 
 463     /**
 464      * Constructs a <code>JList</code> that displays the elements in
 465      * the specified <code>Vector</code>. This constructor creates a read-only
 466      * model for the given {@code Vector}, and then delegates to the constructor
 467      * that takes a {@code ListModel}.
 468      * <p>
 469      * Attempts to pass a {@code null} value to this method results in
 470      * undefined behavior and, most likely, exceptions. The created model
 471      * references the given {@code Vector} directly. Attempts to modify the
 472      * {@code Vector} after constructing the list results in undefined behavior.
 473      *
 474      * @param  listData  the <code>Vector</code> to be loaded into the
 475      *                   data model, {@code non-null}
 476      */
 477     public JList(final Vector<? extends E> listData) {
 478         this (
 479             new AbstractListModel<E>() {
 480                 public int getSize() { return listData.size(); }
 481                 public E getElementAt(int i) { return listData.elementAt(i); }
 482             }
 483         );
 484     }
 485 
 486 
 487     /**
 488      * Constructs a <code>JList</code> with an empty, read-only, model.
 489      */
 490     public JList() {
 491         this (
 492             new AbstractListModel<E>() {
 493               public int getSize() { return 0; }
 494               public E getElementAt(int i) { throw new IndexOutOfBoundsException("No Data Model"); }
 495             }
 496         );
 497     }
 498 
 499 
 500     /**
 501      * Returns the {@code ListUI}, the look and feel object that
 502      * renders this component.
 503      *
 504      * @return the <code>ListUI</code> object that renders this component
 505      */
 506     public ListUI getUI() {
 507         return (ListUI)ui;
 508     }
 509 
 510 
 511     /**
 512      * Sets the {@code ListUI}, the look and feel object that
 513      * renders this component.
 514      *
 515      * @param ui  the <code>ListUI</code> object
 516      * @see UIDefaults#getUI
 517      * @beaninfo
 518      *        bound: true
 519      *       hidden: true
 520      *    attribute: visualUpdate true
 521      *  description: The UI object that implements the Component's LookAndFeel.
 522      */
 523     public void setUI(ListUI ui) {
 524         super.setUI(ui);
 525     }
 526 
 527 
 528     /**
 529      * Resets the {@code ListUI} property by setting it to the value provided
 530      * by the current look and feel. If the current cell renderer was installed
 531      * by the developer (rather than the look and feel itself), this also causes
 532      * the cell renderer and its children to be updated, by calling
 533      * {@code SwingUtilities.updateComponentTreeUI} on it.
 534      *
 535      * @see UIManager#getUI
 536      * @see SwingUtilities#updateComponentTreeUI
 537      */
 538     public void updateUI() {
 539         setUI((ListUI)UIManager.getUI(this));
 540 
 541         ListCellRenderer<? super E> renderer = getCellRenderer();
 542         if (renderer instanceof Component) {
 543             SwingUtilities.updateComponentTreeUI((Component)renderer);
 544         }
 545     }
 546 
 547 
 548     /**
 549      * Returns {@code "ListUI"}, the <code>UIDefaults</code> key used to look
 550      * up the name of the {@code javax.swing.plaf.ListUI} class that defines
 551      * the look and feel for this component.
 552      *
 553      * @return the string "ListUI"
 554      * @see JComponent#getUIClassID
 555      * @see UIDefaults#getUI
 556      */
 557     public String getUIClassID() {
 558         return uiClassID;
 559     }
 560 
 561 
 562     /* -----private-----
 563      * This method is called by setPrototypeCellValue and setCellRenderer
 564      * to update the fixedCellWidth and fixedCellHeight properties from the
 565      * current value of prototypeCellValue (if it's non null).
 566      * <p>
 567      * This method sets fixedCellWidth and fixedCellHeight but does <b>not</b>
 568      * generate PropertyChangeEvents for them.
 569      *
 570      * @see #setPrototypeCellValue
 571      * @see #setCellRenderer
 572      */
 573     private void updateFixedCellSize()
 574     {
 575         ListCellRenderer<? super E> cr = getCellRenderer();
 576         E value = getPrototypeCellValue();
 577 
 578         if ((cr != null) && (value != null)) {
 579             Component c = cr.getListCellRendererComponent(this, value, 0, false, false);
 580 
 581             /* The ListUI implementation will add Component c to its private
 582              * CellRendererPane however we can't assume that's already
 583              * been done here.  So we temporarily set the one "inherited"
 584              * property that may affect the renderer components preferred size:
 585              * its font.
 586              */
 587             Font f = c.getFont();
 588             c.setFont(getFont());
 589 
 590             Dimension d = c.getPreferredSize();
 591             fixedCellWidth = d.width;
 592             fixedCellHeight = d.height;
 593 
 594             c.setFont(f);
 595         }
 596     }
 597 
 598 
 599     /**
 600      * Returns the "prototypical" cell value -- a value used to calculate a
 601      * fixed width and height for cells. This can be {@code null} if there
 602      * is no such value.
 603      *
 604      * @return the value of the {@code prototypeCellValue} property
 605      * @see #setPrototypeCellValue
 606      */
 607     public E getPrototypeCellValue() {
 608         return prototypeCellValue;
 609     }
 610 
 611     /**
 612      * Sets the {@code prototypeCellValue} property, and then (if the new value
 613      * is {@code non-null}), computes the {@code fixedCellWidth} and
 614      * {@code fixedCellHeight} properties by requesting the cell renderer
 615      * component for the given value (and index 0) from the cell renderer, and
 616      * using that component's preferred size.
 617      * <p>
 618      * This method is useful when the list is too long to allow the
 619      * {@code ListUI} to compute the width/height of each cell, and there is a
 620      * single cell value that is known to occupy as much space as any of the
 621      * others, a so-called prototype.
 622      * <p>
 623      * While all three of the {@code prototypeCellValue},
 624      * {@code fixedCellHeight}, and {@code fixedCellWidth} properties may be
 625      * modified by this method, {@code PropertyChangeEvent} notifications are
 626      * only sent when the {@code prototypeCellValue} property changes.
 627      * <p>
 628      * To see an example which sets this property, see the
 629      * <a href="#prototype_example">class description</a> above.
 630      * <p>
 631      * The default value of this property is <code>null</code>.
 632      * <p>
 633      * This is a JavaBeans bound property.
 634      *
 635      * @param prototypeCellValue  the value on which to base
 636      *                          <code>fixedCellWidth</code> and
 637      *                          <code>fixedCellHeight</code>
 638      * @see #getPrototypeCellValue
 639      * @see #setFixedCellWidth
 640      * @see #setFixedCellHeight
 641      * @see JComponent#addPropertyChangeListener
 642      * @beaninfo
 643      *       bound: true
 644      *   attribute: visualUpdate true
 645      * description: The cell prototype value, used to compute cell width and height.
 646      */
 647     public void setPrototypeCellValue(E prototypeCellValue) {
 648         E oldValue = this.prototypeCellValue;
 649         this.prototypeCellValue = prototypeCellValue;
 650 
 651         /* If the prototypeCellValue has changed and is non-null,
 652          * then recompute fixedCellWidth and fixedCellHeight.
 653          */
 654 
 655         if ((prototypeCellValue != null) && !prototypeCellValue.equals(oldValue)) {
 656             updateFixedCellSize();
 657         }
 658 
 659         firePropertyChange("prototypeCellValue", oldValue, prototypeCellValue);
 660     }
 661 
 662 
 663     /**
 664      * Returns the value of the {@code fixedCellWidth} property.
 665      *
 666      * @return the fixed cell width
 667      * @see #setFixedCellWidth
 668      */
 669     public int getFixedCellWidth() {
 670         return fixedCellWidth;
 671     }
 672 
 673     /**
 674      * Sets a fixed value to be used for the width of every cell in the list.
 675      * If {@code width} is -1, cell widths are computed in the {@code ListUI}
 676      * by applying <code>getPreferredSize</code> to the cell renderer component
 677      * for each list element.
 678      * <p>
 679      * The default value of this property is {@code -1}.
 680      * <p>
 681      * This is a JavaBeans bound property.
 682      *
 683      * @param width the width to be used for all cells in the list
 684      * @see #setPrototypeCellValue
 685      * @see #setFixedCellWidth
 686      * @see JComponent#addPropertyChangeListener
 687      * @beaninfo
 688      *       bound: true
 689      *   attribute: visualUpdate true
 690      * description: Defines a fixed cell width when greater than zero.
 691      */
 692     public void setFixedCellWidth(int width) {
 693         int oldValue = fixedCellWidth;
 694         fixedCellWidth = width;
 695         firePropertyChange("fixedCellWidth", oldValue, fixedCellWidth);
 696     }
 697 
 698 
 699     /**
 700      * Returns the value of the {@code fixedCellHeight} property.
 701      *
 702      * @return the fixed cell height
 703      * @see #setFixedCellHeight
 704      */
 705     public int getFixedCellHeight() {
 706         return fixedCellHeight;
 707     }
 708 
 709     /**
 710      * Sets a fixed value to be used for the height of every cell in the list.
 711      * If {@code height} is -1, cell heights are computed in the {@code ListUI}
 712      * by applying <code>getPreferredSize</code> to the cell renderer component
 713      * for each list element.
 714      * <p>
 715      * The default value of this property is {@code -1}.
 716      * <p>
 717      * This is a JavaBeans bound property.
 718      *
 719      * @param height the height to be used for for all cells in the list
 720      * @see #setPrototypeCellValue
 721      * @see #setFixedCellWidth
 722      * @see JComponent#addPropertyChangeListener
 723      * @beaninfo
 724      *       bound: true
 725      *   attribute: visualUpdate true
 726      * description: Defines a fixed cell height when greater than zero.
 727      */
 728     public void setFixedCellHeight(int height) {
 729         int oldValue = fixedCellHeight;
 730         fixedCellHeight = height;
 731         firePropertyChange("fixedCellHeight", oldValue, fixedCellHeight);
 732     }
 733 
 734 
 735     /**
 736      * Returns the object responsible for painting list items.
 737      *
 738      * @return the value of the {@code cellRenderer} property
 739      * @see #setCellRenderer
 740      */
 741     @Transient
 742     public ListCellRenderer<? super E> getCellRenderer() {
 743         return cellRenderer;
 744     }
 745 
 746     /**
 747      * Sets the delegate that is used to paint each cell in the list.
 748      * The job of a cell renderer is discussed in detail in the
 749      * <a href="#renderer">class level documentation</a>.
 750      * <p>
 751      * If the {@code prototypeCellValue} property is {@code non-null},
 752      * setting the cell renderer also causes the {@code fixedCellWidth} and
 753      * {@code fixedCellHeight} properties to be re-calculated. Only one
 754      * <code>PropertyChangeEvent</code> is generated however -
 755      * for the <code>cellRenderer</code> property.
 756      * <p>
 757      * The default value of this property is provided by the {@code ListUI}
 758      * delegate, i.e. by the look and feel implementation.
 759      * <p>
 760      * This is a JavaBeans bound property.
 761      *
 762      * @param cellRenderer the <code>ListCellRenderer</code>
 763      *                          that paints list cells
 764      * @see #getCellRenderer
 765      * @beaninfo
 766      *       bound: true
 767      *   attribute: visualUpdate true
 768      * description: The component used to draw the cells.
 769      */
 770     public void setCellRenderer(ListCellRenderer<? super E> cellRenderer) {
 771         ListCellRenderer<? super E> oldValue = this.cellRenderer;
 772         this.cellRenderer = cellRenderer;
 773 
 774         /* If the cellRenderer has changed and prototypeCellValue
 775          * was set, then recompute fixedCellWidth and fixedCellHeight.
 776          */
 777         if ((cellRenderer != null) && !cellRenderer.equals(oldValue)) {
 778             updateFixedCellSize();
 779         }
 780 
 781         firePropertyChange("cellRenderer", oldValue, cellRenderer);
 782     }
 783 
 784 
 785     /**
 786      * Returns the color used to draw the foreground of selected items.
 787      * {@code DefaultListCellRenderer} uses this color to draw the foreground
 788      * of items in the selected state, as do the renderers installed by most
 789      * {@code ListUI} implementations.
 790      *
 791      * @return the color to draw the foreground of selected items
 792      * @see #setSelectionForeground
 793      * @see DefaultListCellRenderer
 794      */
 795     public Color getSelectionForeground() {
 796         return selectionForeground;
 797     }
 798 
 799 
 800     /**
 801      * Sets the color used to draw the foreground of selected items, which
 802      * cell renderers can use to render text and graphics.
 803      * {@code DefaultListCellRenderer} uses this color to draw the foreground
 804      * of items in the selected state, as do the renderers installed by most
 805      * {@code ListUI} implementations.
 806      * <p>
 807      * The default value of this property is defined by the look and feel
 808      * implementation.
 809      * <p>
 810      * This is a JavaBeans bound property.
 811      *
 812      * @param selectionForeground  the {@code Color} to use in the foreground
 813      *                             for selected list items
 814      * @see #getSelectionForeground
 815      * @see #setSelectionBackground
 816      * @see #setForeground
 817      * @see #setBackground
 818      * @see #setFont
 819      * @see DefaultListCellRenderer
 820      * @beaninfo
 821      *       bound: true
 822      *   attribute: visualUpdate true
 823      * description: The foreground color of selected cells.
 824      */
 825     public void setSelectionForeground(Color selectionForeground) {
 826         Color oldValue = this.selectionForeground;
 827         this.selectionForeground = selectionForeground;
 828         firePropertyChange("selectionForeground", oldValue, selectionForeground);
 829     }
 830 
 831 
 832     /**
 833      * Returns the color used to draw the background of selected items.
 834      * {@code DefaultListCellRenderer} uses this color to draw the background
 835      * of items in the selected state, as do the renderers installed by most
 836      * {@code ListUI} implementations.
 837      *
 838      * @return the color to draw the background of selected items
 839      * @see #setSelectionBackground
 840      * @see DefaultListCellRenderer
 841      */
 842     public Color getSelectionBackground() {
 843         return selectionBackground;
 844     }
 845 
 846 
 847     /**
 848      * Sets the color used to draw the background of selected items, which
 849      * cell renderers can use fill selected cells.
 850      * {@code DefaultListCellRenderer} uses this color to fill the background
 851      * of items in the selected state, as do the renderers installed by most
 852      * {@code ListUI} implementations.
 853      * <p>
 854      * The default value of this property is defined by the look
 855      * and feel implementation.
 856      * <p>
 857      * This is a JavaBeans bound property.
 858      *
 859      * @param selectionBackground  the {@code Color} to use for the
 860      *                             background of selected cells
 861      * @see #getSelectionBackground
 862      * @see #setSelectionForeground
 863      * @see #setForeground
 864      * @see #setBackground
 865      * @see #setFont
 866      * @see DefaultListCellRenderer
 867      * @beaninfo
 868      *       bound: true
 869      *   attribute: visualUpdate true
 870      * description: The background color of selected cells.
 871      */
 872     public void setSelectionBackground(Color selectionBackground) {
 873         Color oldValue = this.selectionBackground;
 874         this.selectionBackground = selectionBackground;
 875         firePropertyChange("selectionBackground", oldValue, selectionBackground);
 876     }
 877 
 878 
 879     /**
 880      * Returns the value of the {@code visibleRowCount} property. See the
 881      * documentation for {@link #setVisibleRowCount} for details on how to
 882      * interpret this value.
 883      *
 884      * @return the value of the {@code visibleRowCount} property.
 885      * @see #setVisibleRowCount
 886      */
 887     public int getVisibleRowCount() {
 888         return visibleRowCount;
 889     }
 890 
 891     /**
 892      * Sets the {@code visibleRowCount} property, which has different meanings
 893      * depending on the layout orientation: For a {@code VERTICAL} layout
 894      * orientation, this sets the preferred number of rows to display without
 895      * requiring scrolling; for other orientations, it affects the wrapping of
 896      * cells.
 897      * <p>
 898      * In {@code VERTICAL} orientation:<br>
 899      * Setting this property affects the return value of the
 900      * {@link #getPreferredScrollableViewportSize} method, which is used to
 901      * calculate the preferred size of an enclosing viewport. See that method's
 902      * documentation for more details.
 903      * <p>
 904      * In {@code HORIZONTAL_WRAP} and {@code VERTICAL_WRAP} orientations:<br>
 905      * This affects how cells are wrapped. See the documentation of
 906      * {@link #setLayoutOrientation} for more details.
 907      * <p>
 908      * The default value of this property is {@code 8}.
 909      * <p>
 910      * Calling this method with a negative value results in the property
 911      * being set to {@code 0}.
 912      * <p>
 913      * This is a JavaBeans bound property.
 914      *
 915      * @param visibleRowCount  an integer specifying the preferred number of
 916      *                         rows to display without requiring scrolling
 917      * @see #getVisibleRowCount
 918      * @see #getPreferredScrollableViewportSize
 919      * @see #setLayoutOrientation
 920      * @see JComponent#getVisibleRect
 921      * @see JViewport
 922      * @beaninfo
 923      *       bound: true
 924      *   attribute: visualUpdate true
 925      * description: The preferred number of rows to display without
 926      *              requiring scrolling
 927      */
 928     public void setVisibleRowCount(int visibleRowCount) {
 929         int oldValue = this.visibleRowCount;
 930         this.visibleRowCount = Math.max(0, visibleRowCount);
 931         firePropertyChange("visibleRowCount", oldValue, visibleRowCount);
 932     }
 933 
 934 
 935     /**
 936      * Returns the layout orientation property for the list: {@code VERTICAL}
 937      * if the layout is a single column of cells, {@code VERTICAL_WRAP} if the
 938      * layout is "newspaper style" with the content flowing vertically then
 939      * horizontally, or {@code HORIZONTAL_WRAP} if the layout is "newspaper
 940      * style" with the content flowing horizontally then vertically.
 941      *
 942      * @return the value of the {@code layoutOrientation} property
 943      * @see #setLayoutOrientation
 944      * @since 1.4
 945      */
 946     public int getLayoutOrientation() {
 947         return layoutOrientation;
 948     }
 949 
 950 
 951     /**
 952      * Defines the way list cells are layed out. Consider a {@code JList}
 953      * with five cells. Cells can be layed out in one of the following ways:
 954      *
 955      * <pre>
 956      * VERTICAL:          0
 957      *                    1
 958      *                    2
 959      *                    3
 960      *                    4
 961      *
 962      * HORIZONTAL_WRAP:   0  1  2
 963      *                    3  4
 964      *
 965      * VERTICAL_WRAP:     0  3
 966      *                    1  4
 967      *                    2
 968      * </pre>
 969      * <p>
 970      * A description of these layouts follows:
 971      *
 972      * <table border="1"
 973      *  summary="Describes layouts VERTICAL, HORIZONTAL_WRAP, and VERTICAL_WRAP">
 974      *   <tr><th><p style="text-align:left">Value</p></th><th><p style="text-align:left">Description</p></th></tr>
 975      *   <tr><td><code>VERTICAL</code>
 976      *       <td>Cells are layed out vertically in a single column.
 977      *   <tr><td><code>HORIZONTAL_WRAP</code>
 978      *       <td>Cells are layed out horizontally, wrapping to a new row as
 979      *           necessary. If the {@code visibleRowCount} property is less than
 980      *           or equal to zero, wrapping is determined by the width of the
 981      *           list; otherwise wrapping is done in such a way as to ensure
 982      *           {@code visibleRowCount} rows in the list.
 983      *   <tr><td><code>VERTICAL_WRAP</code>
 984      *       <td>Cells are layed out vertically, wrapping to a new column as
 985      *           necessary. If the {@code visibleRowCount} property is less than
 986      *           or equal to zero, wrapping is determined by the height of the
 987      *           list; otherwise wrapping is done at {@code visibleRowCount} rows.
 988      *  </table>
 989      * <p>
 990      * The default value of this property is <code>VERTICAL</code>.
 991      *
 992      * @param layoutOrientation the new layout orientation, one of:
 993      *        {@code VERTICAL}, {@code HORIZONTAL_WRAP} or {@code VERTICAL_WRAP}
 994      * @see #getLayoutOrientation
 995      * @see #setVisibleRowCount
 996      * @see #getScrollableTracksViewportHeight
 997      * @see #getScrollableTracksViewportWidth
 998      * @throws IllegalArgumentException if {@code layoutOrientation} isn't one of the
 999      *         allowable values
1000      * @since 1.4
1001      * @beaninfo
1002      *       bound: true
1003      *   attribute: visualUpdate true
1004      * description: Defines the way list cells are layed out.
1005      *        enum: VERTICAL JList.VERTICAL
1006      *              HORIZONTAL_WRAP JList.HORIZONTAL_WRAP
1007      *              VERTICAL_WRAP JList.VERTICAL_WRAP
1008      */
1009     public void setLayoutOrientation(int layoutOrientation) {
1010         int oldValue = this.layoutOrientation;
1011         switch (layoutOrientation) {
1012         case VERTICAL:
1013         case VERTICAL_WRAP:
1014         case HORIZONTAL_WRAP:
1015             this.layoutOrientation = layoutOrientation;
1016             firePropertyChange("layoutOrientation", oldValue, layoutOrientation);
1017             break;
1018         default:
1019             throw new IllegalArgumentException("layoutOrientation must be one of: VERTICAL, HORIZONTAL_WRAP or VERTICAL_WRAP");
1020         }
1021     }
1022 
1023 
1024     /**
1025      * Returns the smallest list index that is currently visible.
1026      * In a left-to-right {@code componentOrientation}, the first visible
1027      * cell is found closest to the list's upper-left corner. In right-to-left
1028      * orientation, it is found closest to the upper-right corner.
1029      * If nothing is visible or the list is empty, {@code -1} is returned.
1030      * Note that the returned cell may only be partially visible.
1031      *
1032      * @return the index of the first visible cell
1033      * @see #getLastVisibleIndex
1034      * @see JComponent#getVisibleRect
1035      */
1036     public int getFirstVisibleIndex() {
1037         Rectangle r = getVisibleRect();
1038         int first;
1039         if (this.getComponentOrientation().isLeftToRight()) {
1040             first = locationToIndex(r.getLocation());
1041         } else {
1042             first = locationToIndex(new Point((r.x + r.width) - 1, r.y));
1043         }
1044         if (first != -1) {
1045             Rectangle bounds = getCellBounds(first, first);
1046             if (bounds != null) {
1047                 SwingUtilities.computeIntersection(r.x, r.y, r.width, r.height, bounds);
1048                 if (bounds.width == 0 || bounds.height == 0) {
1049                     first = -1;
1050                 }
1051             }
1052         }
1053         return first;
1054     }
1055 
1056 
1057     /**
1058      * Returns the largest list index that is currently visible.
1059      * If nothing is visible or the list is empty, {@code -1} is returned.
1060      * Note that the returned cell may only be partially visible.
1061      *
1062      * @return the index of the last visible cell
1063      * @see #getFirstVisibleIndex
1064      * @see JComponent#getVisibleRect
1065      */
1066     public int getLastVisibleIndex() {
1067         boolean leftToRight = this.getComponentOrientation().isLeftToRight();
1068         Rectangle r = getVisibleRect();
1069         Point lastPoint;
1070         if (leftToRight) {
1071             lastPoint = new Point((r.x + r.width) - 1, (r.y + r.height) - 1);
1072         } else {
1073             lastPoint = new Point(r.x, (r.y + r.height) - 1);
1074         }
1075         int location = locationToIndex(lastPoint);
1076 
1077         if (location != -1) {
1078             Rectangle bounds = getCellBounds(location, location);
1079 
1080             if (bounds != null) {
1081                 SwingUtilities.computeIntersection(r.x, r.y, r.width, r.height, bounds);
1082                 if (bounds.width == 0 || bounds.height == 0) {
1083                     // Try the top left(LTR) or top right(RTL) corner, and
1084                     // then go across checking each cell for HORIZONTAL_WRAP.
1085                     // Try the lower left corner, and then go across checking
1086                     // each cell for other list layout orientation.
1087                     boolean isHorizontalWrap =
1088                         (getLayoutOrientation() == HORIZONTAL_WRAP);
1089                     Point visibleLocation = isHorizontalWrap ?
1090                         new Point(lastPoint.x, r.y) :
1091                         new Point(r.x, lastPoint.y);
1092                     int last;
1093                     int visIndex = -1;
1094                     int lIndex = location;
1095                     location = -1;
1096 
1097                     do {
1098                         last = visIndex;
1099                         visIndex = locationToIndex(visibleLocation);
1100 
1101                         if (visIndex != -1) {
1102                             bounds = getCellBounds(visIndex, visIndex);
1103                             if (visIndex != lIndex && bounds != null &&
1104                                 bounds.contains(visibleLocation)) {
1105                                 location = visIndex;
1106                                 if (isHorizontalWrap) {
1107                                     visibleLocation.y = bounds.y + bounds.height;
1108                                     if (visibleLocation.y >= lastPoint.y) {
1109                                         // Past visible region, bail.
1110                                         last = visIndex;
1111                                     }
1112                                 }
1113                                 else {
1114                                     visibleLocation.x = bounds.x + bounds.width;
1115                                     if (visibleLocation.x >= lastPoint.x) {
1116                                         // Past visible region, bail.
1117                                         last = visIndex;
1118                                     }
1119                                 }
1120 
1121                             }
1122                             else {
1123                                 last = visIndex;
1124                             }
1125                         }
1126                     } while (visIndex != -1 && last != visIndex);
1127                 }
1128             }
1129         }
1130         return location;
1131     }
1132 
1133 
1134     /**
1135      * Scrolls the list within an enclosing viewport to make the specified
1136      * cell completely visible. This calls {@code scrollRectToVisible} with
1137      * the bounds of the specified cell. For this method to work, the
1138      * {@code JList} must be within a <code>JViewport</code>.
1139      * <p>
1140      * If the given index is outside the list's range of cells, this method
1141      * results in nothing.
1142      *
1143      * @param index  the index of the cell to make visible
1144      * @see JComponent#scrollRectToVisible
1145      * @see #getVisibleRect
1146      */
1147     public void ensureIndexIsVisible(int index) {
1148         Rectangle cellBounds = getCellBounds(index, index);
1149         if (cellBounds != null) {
1150             scrollRectToVisible(cellBounds);
1151         }
1152     }
1153 
1154     /**
1155      * Turns on or off automatic drag handling. In order to enable automatic
1156      * drag handling, this property should be set to {@code true}, and the
1157      * list's {@code TransferHandler} needs to be {@code non-null}.
1158      * The default value of the {@code dragEnabled} property is {@code false}.
1159      * <p>
1160      * The job of honoring this property, and recognizing a user drag gesture,
1161      * lies with the look and feel implementation, and in particular, the list's
1162      * {@code ListUI}. When automatic drag handling is enabled, most look and
1163      * feels (including those that subclass {@code BasicLookAndFeel}) begin a
1164      * drag and drop operation whenever the user presses the mouse button over
1165      * an item and then moves the mouse a few pixels. Setting this property to
1166      * {@code true} can therefore have a subtle effect on how selections behave.
1167      * <p>
1168      * If a look and feel is used that ignores this property, you can still
1169      * begin a drag and drop operation by calling {@code exportAsDrag} on the
1170      * list's {@code TransferHandler}.
1171      *
1172      * @param b whether or not to enable automatic drag handling
1173      * @exception HeadlessException if
1174      *            <code>b</code> is <code>true</code> and
1175      *            <code>GraphicsEnvironment.isHeadless()</code>
1176      *            returns <code>true</code>
1177      * @see java.awt.GraphicsEnvironment#isHeadless
1178      * @see #getDragEnabled
1179      * @see #setTransferHandler
1180      * @see TransferHandler
1181      * @since 1.4
1182      *
1183      * @beaninfo
1184      *  description: determines whether automatic drag handling is enabled
1185      *        bound: false
1186      */
1187     public void setDragEnabled(boolean b) {
1188         if (b && GraphicsEnvironment.isHeadless()) {
1189             throw new HeadlessException();
1190         }
1191         dragEnabled = b;
1192     }
1193 
1194     /**
1195      * Returns whether or not automatic drag handling is enabled.
1196      *
1197      * @return the value of the {@code dragEnabled} property
1198      * @see #setDragEnabled
1199      * @since 1.4
1200      */
1201     public boolean getDragEnabled() {
1202         return dragEnabled;
1203     }
1204 
1205     /**
1206      * Sets the drop mode for this component. For backward compatibility,
1207      * the default for this property is <code>DropMode.USE_SELECTION</code>.
1208      * Usage of one of the other modes is recommended, however, for an
1209      * improved user experience. <code>DropMode.ON</code>, for instance,
1210      * offers similar behavior of showing items as selected, but does so without
1211      * affecting the actual selection in the list.
1212      * <p>
1213      * <code>JList</code> supports the following drop modes:
1214      * <ul>
1215      *    <li><code>DropMode.USE_SELECTION</code></li>
1216      *    <li><code>DropMode.ON</code></li>
1217      *    <li><code>DropMode.INSERT</code></li>
1218      *    <li><code>DropMode.ON_OR_INSERT</code></li>
1219      * </ul>
1220      * The drop mode is only meaningful if this component has a
1221      * <code>TransferHandler</code> that accepts drops.
1222      *
1223      * @param dropMode the drop mode to use
1224      * @throws IllegalArgumentException if the drop mode is unsupported
1225      *         or <code>null</code>
1226      * @see #getDropMode
1227      * @see #getDropLocation
1228      * @see #setTransferHandler
1229      * @see TransferHandler
1230      * @since 1.6
1231      */
1232     public final void setDropMode(DropMode dropMode) {
1233         if (dropMode != null) {
1234             switch (dropMode) {
1235                 case USE_SELECTION:
1236                 case ON:
1237                 case INSERT:
1238                 case ON_OR_INSERT:
1239                     this.dropMode = dropMode;
1240                     return;
1241             }
1242         }
1243 
1244         throw new IllegalArgumentException(dropMode + ": Unsupported drop mode for list");
1245     }
1246 
1247     /**
1248      * Returns the drop mode for this component.
1249      *
1250      * @return the drop mode for this component
1251      * @see #setDropMode
1252      * @since 1.6
1253      */
1254     public final DropMode getDropMode() {
1255         return dropMode;
1256     }
1257 
1258     /**
1259      * Calculates a drop location in this component, representing where a
1260      * drop at the given point should insert data.
1261      *
1262      * @param p the point to calculate a drop location for
1263      * @return the drop location, or <code>null</code>
1264      */
1265     DropLocation dropLocationForPoint(Point p) {
1266         DropLocation location = null;
1267         Rectangle rect = null;
1268 
1269         int index = locationToIndex(p);
1270         if (index != -1) {
1271             rect = getCellBounds(index, index);
1272         }
1273 
1274         switch(dropMode) {
1275             case USE_SELECTION:
1276             case ON:
1277                 location = new DropLocation(p,
1278                     (rect != null && rect.contains(p)) ? index : -1,
1279                     false);
1280 
1281                 break;
1282             case INSERT:
1283                 if (index == -1) {
1284                     location = new DropLocation(p, getModel().getSize(), true);
1285                     break;
1286                 }
1287 
1288                 if (layoutOrientation == HORIZONTAL_WRAP) {
1289                     boolean ltr = getComponentOrientation().isLeftToRight();
1290 
1291                     if (SwingUtilities2.liesInHorizontal(rect, p, ltr, false) == TRAILING) {
1292                         index++;
1293                     // special case for below all cells
1294                     } else if (index == getModel().getSize() - 1 && p.y >= rect.y + rect.height) {
1295                         index++;
1296                     }
1297                 } else {
1298                     if (SwingUtilities2.liesInVertical(rect, p, false) == TRAILING) {
1299                         index++;
1300                     }
1301                 }
1302 
1303                 location = new DropLocation(p, index, true);
1304 
1305                 break;
1306             case ON_OR_INSERT:
1307                 if (index == -1) {
1308                     location = new DropLocation(p, getModel().getSize(), true);
1309                     break;
1310                 }
1311 
1312                 boolean between = false;
1313 
1314                 if (layoutOrientation == HORIZONTAL_WRAP) {
1315                     boolean ltr = getComponentOrientation().isLeftToRight();
1316 
1317                     Section section = SwingUtilities2.liesInHorizontal(rect, p, ltr, true);
1318                     if (section == TRAILING) {
1319                         index++;
1320                         between = true;
1321                     // special case for below all cells
1322                     } else if (index == getModel().getSize() - 1 && p.y >= rect.y + rect.height) {
1323                         index++;
1324                         between = true;
1325                     } else if (section == LEADING) {
1326                         between = true;
1327                     }
1328                 } else {
1329                     Section section = SwingUtilities2.liesInVertical(rect, p, true);
1330                     if (section == LEADING) {
1331                         between = true;
1332                     } else if (section == TRAILING) {
1333                         index++;
1334                         between = true;
1335                     }
1336                 }
1337 
1338                 location = new DropLocation(p, index, between);
1339 
1340                 break;
1341             default:
1342                 assert false : "Unexpected drop mode";
1343         }
1344 
1345         return location;
1346     }
1347 
1348     /**
1349      * Called to set or clear the drop location during a DnD operation.
1350      * In some cases, the component may need to use it's internal selection
1351      * temporarily to indicate the drop location. To help facilitate this,
1352      * this method returns and accepts as a parameter a state object.
1353      * This state object can be used to store, and later restore, the selection
1354      * state. Whatever this method returns will be passed back to it in
1355      * future calls, as the state parameter. If it wants the DnD system to
1356      * continue storing the same state, it must pass it back every time.
1357      * Here's how this is used:
1358      * <p>
1359      * Let's say that on the first call to this method the component decides
1360      * to save some state (because it is about to use the selection to show
1361      * a drop index). It can return a state object to the caller encapsulating
1362      * any saved selection state. On a second call, let's say the drop location
1363      * is being changed to something else. The component doesn't need to
1364      * restore anything yet, so it simply passes back the same state object
1365      * to have the DnD system continue storing it. Finally, let's say this
1366      * method is messaged with <code>null</code>. This means DnD
1367      * is finished with this component for now, meaning it should restore
1368      * state. At this point, it can use the state parameter to restore
1369      * said state, and of course return <code>null</code> since there's
1370      * no longer anything to store.
1371      *
1372      * @param location the drop location (as calculated by
1373      *        <code>dropLocationForPoint</code>) or <code>null</code>
1374      *        if there's no longer a valid drop location
1375      * @param state the state object saved earlier for this component,
1376      *        or <code>null</code>
1377      * @param forDrop whether or not the method is being called because an
1378      *        actual drop occurred
1379      * @return any saved state for this component, or <code>null</code> if none
1380      */
1381     Object setDropLocation(TransferHandler.DropLocation location,
1382                            Object state,
1383                            boolean forDrop) {
1384 
1385         Object retVal = null;
1386         DropLocation listLocation = (DropLocation)location;
1387 
1388         if (dropMode == DropMode.USE_SELECTION) {
1389             if (listLocation == null) {
1390                 if (!forDrop && state != null) {
1391                     setSelectedIndices(((int[][])state)[0]);
1392 
1393                     int anchor = ((int[][])state)[1][0];
1394                     int lead = ((int[][])state)[1][1];
1395 
1396                     SwingUtilities2.setLeadAnchorWithoutSelection(
1397                             getSelectionModel(), lead, anchor);
1398                 }
1399             } else {
1400                 if (dropLocation == null) {
1401                     int[] inds = getSelectedIndices();
1402                     retVal = new int[][] {inds, {getAnchorSelectionIndex(),
1403                                                  getLeadSelectionIndex()}};
1404                 } else {
1405                     retVal = state;
1406                 }
1407 
1408                 int index = listLocation.getIndex();
1409                 if (index == -1) {
1410                     clearSelection();
1411                     getSelectionModel().setAnchorSelectionIndex(-1);
1412                     getSelectionModel().setLeadSelectionIndex(-1);
1413                 } else {
1414                     setSelectionInterval(index, index);
1415                 }
1416             }
1417         }
1418 
1419         DropLocation old = dropLocation;
1420         dropLocation = listLocation;
1421         firePropertyChange("dropLocation", old, dropLocation);
1422 
1423         return retVal;
1424     }
1425 
1426     /**
1427      * Returns the location that this component should visually indicate
1428      * as the drop location during a DnD operation over the component,
1429      * or {@code null} if no location is to currently be shown.
1430      * <p>
1431      * This method is not meant for querying the drop location
1432      * from a {@code TransferHandler}, as the drop location is only
1433      * set after the {@code TransferHandler}'s <code>canImport</code>
1434      * has returned and has allowed for the location to be shown.
1435      * <p>
1436      * When this property changes, a property change event with
1437      * name "dropLocation" is fired by the component.
1438      * <p>
1439      * By default, responsibility for listening for changes to this property
1440      * and indicating the drop location visually lies with the list's
1441      * {@code ListUI}, which may paint it directly and/or install a cell
1442      * renderer to do so. Developers wishing to implement custom drop location
1443      * painting and/or replace the default cell renderer, may need to honor
1444      * this property.
1445      *
1446      * @return the drop location
1447      * @see #setDropMode
1448      * @see TransferHandler#canImport(TransferHandler.TransferSupport)
1449      * @since 1.6
1450      */
1451     public final DropLocation getDropLocation() {
1452         return dropLocation;
1453     }
1454 
1455     /**
1456      * Returns the next list element whose {@code toString} value
1457      * starts with the given prefix.
1458      *
1459      * @param prefix the string to test for a match
1460      * @param startIndex the index for starting the search
1461      * @param bias the search direction, either
1462      * Position.Bias.Forward or Position.Bias.Backward.
1463      * @return the index of the next list element that
1464      * starts with the prefix; otherwise {@code -1}
1465      * @exception IllegalArgumentException if prefix is {@code null}
1466      * or startIndex is out of bounds
1467      * @since 1.4
1468      */
1469     public int getNextMatch(String prefix, int startIndex, Position.Bias bias) {
1470         ListModel<E> model = getModel();
1471         int max = model.getSize();
1472         if (prefix == null) {
1473             throw new IllegalArgumentException();
1474         }
1475         if (startIndex < 0 || startIndex >= max) {
1476             throw new IllegalArgumentException();
1477         }
1478         prefix = prefix.toUpperCase();
1479 
1480         // start search from the next element after the selected element
1481         int increment = (bias == Position.Bias.Forward) ? 1 : -1;
1482         int index = startIndex;
1483         do {
1484             E element = model.getElementAt(index);
1485 
1486             if (element != null) {
1487                 String string;
1488 
1489                 if (element instanceof String) {
1490                     string = ((String)element).toUpperCase();
1491                 }
1492                 else {
1493                     string = element.toString();
1494                     if (string != null) {
1495                         string = string.toUpperCase();
1496                     }
1497                 }
1498 
1499                 if (string != null && string.startsWith(prefix)) {
1500                     return index;
1501                 }
1502             }
1503             index = (index + increment + max) % max;
1504         } while (index != startIndex);
1505         return -1;
1506     }
1507 
1508     /**
1509      * Returns the tooltip text to be used for the given event. This overrides
1510      * {@code JComponent}'s {@code getToolTipText} to first check the cell
1511      * renderer component for the cell over which the event occurred, returning
1512      * its tooltip text, if any. This implementation allows you to specify
1513      * tooltip text on the cell level, by using {@code setToolTipText} on your
1514      * cell renderer component.
1515      * <p>
1516      * <strong>Note:</strong> For <code>JList</code> to properly display the
1517      * tooltips of its renderers in this manner, <code>JList</code> must be a
1518      * registered component with the <code>ToolTipManager</code>. This registration
1519      * is done automatically in the constructor. However, if at a later point
1520      * <code>JList</code> is unregistered, by way of a call to
1521      * {@code setToolTipText(null)}, tips from the renderers will no longer display.
1522      *
1523      * @param event the {@code MouseEvent} to fetch the tooltip text for
1524      * @see JComponent#setToolTipText
1525      * @see JComponent#getToolTipText
1526      */
1527     public String getToolTipText(MouseEvent event) {
1528         if(event != null) {
1529             Point p = event.getPoint();
1530             int index = locationToIndex(p);
1531             ListCellRenderer<? super E> r = getCellRenderer();
1532             Rectangle cellBounds;
1533 
1534             if (index != -1 && r != null && (cellBounds =
1535                                getCellBounds(index, index)) != null &&
1536                                cellBounds.contains(p.x, p.y)) {
1537                 ListSelectionModel lsm = getSelectionModel();
1538                 Component rComponent = r.getListCellRendererComponent(
1539                            this, getModel().getElementAt(index), index,
1540                            lsm.isSelectedIndex(index),
1541                            (hasFocus() && (lsm.getLeadSelectionIndex() ==
1542                                            index)));
1543 
1544                 if(rComponent instanceof JComponent) {
1545                     MouseEvent      newEvent;
1546 
1547                     p.translate(-cellBounds.x, -cellBounds.y);
1548                     newEvent = new MouseEvent(rComponent, event.getID(),
1549                                               event.getWhen(),
1550                                               event.getModifiers(),
1551                                               p.x, p.y,
1552                                               event.getXOnScreen(),
1553                                               event.getYOnScreen(),
1554                                               event.getClickCount(),
1555                                               event.isPopupTrigger(),
1556                                               MouseEvent.NOBUTTON);
1557 
1558                     String tip = ((JComponent)rComponent).getToolTipText(
1559                                               newEvent);
1560 
1561                     if (tip != null) {
1562                         return tip;
1563                     }
1564                 }
1565             }
1566         }
1567         return super.getToolTipText();
1568     }
1569 
1570     /**
1571      * --- ListUI Delegations ---
1572      */
1573 
1574 
1575     /**
1576      * Returns the cell index closest to the given location in the list's
1577      * coordinate system. To determine if the cell actually contains the
1578      * specified location, compare the point against the cell's bounds,
1579      * as provided by {@code getCellBounds}. This method returns {@code -1}
1580      * if the model is empty
1581      * <p>
1582      * This is a cover method that delegates to the method of the same name
1583      * in the list's {@code ListUI}. It returns {@code -1} if the list has
1584      * no {@code ListUI}.
1585      *
1586      * @param location the coordinates of the point
1587      * @return the cell index closest to the given location, or {@code -1}
1588      */
1589     public int locationToIndex(Point location) {
1590         ListUI ui = getUI();
1591         return (ui != null) ? ui.locationToIndex(this, location) : -1;
1592     }
1593 
1594 
1595     /**
1596      * Returns the origin of the specified item in the list's coordinate
1597      * system. This method returns {@code null} if the index isn't valid.
1598      * <p>
1599      * This is a cover method that delegates to the method of the same name
1600      * in the list's {@code ListUI}. It returns {@code null} if the list has
1601      * no {@code ListUI}.
1602      *
1603      * @param index the cell index
1604      * @return the origin of the cell, or {@code null}
1605      */
1606     public Point indexToLocation(int index) {
1607         ListUI ui = getUI();
1608         return (ui != null) ? ui.indexToLocation(this, index) : null;
1609     }
1610 
1611 
1612     /**
1613      * Returns the bounding rectangle, in the list's coordinate system,
1614      * for the range of cells specified by the two indices.
1615      * These indices can be supplied in any order.
1616      * <p>
1617      * If the smaller index is outside the list's range of cells, this method
1618      * returns {@code null}. If the smaller index is valid, but the larger
1619      * index is outside the list's range, the bounds of just the first index
1620      * is returned. Otherwise, the bounds of the valid range is returned.
1621      * <p>
1622      * This is a cover method that delegates to the method of the same name
1623      * in the list's {@code ListUI}. It returns {@code null} if the list has
1624      * no {@code ListUI}.
1625      *
1626      * @param index0 the first index in the range
1627      * @param index1 the second index in the range
1628      * @return the bounding rectangle for the range of cells, or {@code null}
1629      */
1630     public Rectangle getCellBounds(int index0, int index1) {
1631         ListUI ui = getUI();
1632         return (ui != null) ? ui.getCellBounds(this, index0, index1) : null;
1633     }
1634 
1635 
1636     /**
1637      * --- ListModel Support ---
1638      */
1639 
1640 
1641     /**
1642      * Returns the data model that holds the list of items displayed
1643      * by the <code>JList</code> component.
1644      *
1645      * @return the <code>ListModel</code> that provides the displayed
1646      *                          list of items
1647      * @see #setModel
1648      */
1649     public ListModel<E> getModel() {
1650         return dataModel;
1651     }
1652 
1653     /**
1654      * Sets the model that represents the contents or "value" of the
1655      * list, notifies property change listeners, and then clears the
1656      * list's selection.
1657      * <p>
1658      * This is a JavaBeans bound property.
1659      *
1660      * @param model  the <code>ListModel</code> that provides the
1661      *                                          list of items for display
1662      * @exception IllegalArgumentException  if <code>model</code> is
1663      *                                          <code>null</code>
1664      * @see #getModel
1665      * @see #clearSelection
1666      * @beaninfo
1667      *       bound: true
1668      *   attribute: visualUpdate true
1669      * description: The object that contains the data to be drawn by this JList.
1670      */
1671     public void setModel(ListModel<E> model) {
1672         if (model == null) {
1673             throw new IllegalArgumentException("model must be non null");
1674         }
1675         ListModel<E> oldValue = dataModel;
1676         dataModel = model;
1677         firePropertyChange("model", oldValue, dataModel);
1678         clearSelection();
1679     }
1680 
1681 
1682     /**
1683      * Constructs a read-only <code>ListModel</code> from an array of items,
1684      * and calls {@code setModel} with this model.
1685      * <p>
1686      * Attempts to pass a {@code null} value to this method results in
1687      * undefined behavior and, most likely, exceptions. The created model
1688      * references the given array directly. Attempts to modify the array
1689      * after invoking this method results in undefined behavior.
1690      *
1691      * @param listData an array of {@code E} containing the items to
1692      *        display in the list
1693      * @see #setModel
1694      */
1695     public void setListData(final E[] listData) {
1696         setModel (
1697             new AbstractListModel<E>() {
1698                 public int getSize() { return listData.length; }
1699                 public E getElementAt(int i) { return listData[i]; }
1700             }
1701         );
1702     }
1703 
1704 
1705     /**
1706      * Constructs a read-only <code>ListModel</code> from a <code>Vector</code>
1707      * and calls {@code setModel} with this model.
1708      * <p>
1709      * Attempts to pass a {@code null} value to this method results in
1710      * undefined behavior and, most likely, exceptions. The created model
1711      * references the given {@code Vector} directly. Attempts to modify the
1712      * {@code Vector} after invoking this method results in undefined behavior.
1713      *
1714      * @param listData a <code>Vector</code> containing the items to
1715      *                                          display in the list
1716      * @see #setModel
1717      */
1718     public void setListData(final Vector<? extends E> listData) {
1719         setModel (
1720             new AbstractListModel<E>() {
1721                 public int getSize() { return listData.size(); }
1722                 public E getElementAt(int i) { return listData.elementAt(i); }
1723             }
1724         );
1725     }
1726 
1727 
1728     /**
1729      * --- ListSelectionModel delegations and extensions ---
1730      */
1731 
1732 
1733     /**
1734      * Returns an instance of {@code DefaultListSelectionModel}; called
1735      * during construction to initialize the list's selection model
1736      * property.
1737      *
1738      * @return a {@code DefaultListSelecitonModel}, used to initialize
1739      *         the list's selection model property during construction
1740      * @see #setSelectionModel
1741      * @see DefaultListSelectionModel
1742      */
1743     protected ListSelectionModel createSelectionModel() {
1744         return new DefaultListSelectionModel();
1745     }
1746 
1747 
1748     /**
1749      * Returns the current selection model. The selection model maintains the
1750      * selection state of the list. See the class level documentation for more
1751      * details.
1752      *
1753      * @return the <code>ListSelectionModel</code> that maintains the
1754      *         list's selections
1755      *
1756      * @see #setSelectionModel
1757      * @see ListSelectionModel
1758      */
1759     public ListSelectionModel getSelectionModel() {
1760         return selectionModel;
1761     }
1762 
1763 
1764     /**
1765      * Notifies {@code ListSelectionListener}s added directly to the list
1766      * of selection changes made to the selection model. {@code JList}
1767      * listens for changes made to the selection in the selection model,
1768      * and forwards notification to listeners added to the list directly,
1769      * by calling this method.
1770      * <p>
1771      * This method constructs a {@code ListSelectionEvent} with this list
1772      * as the source, and the specified arguments, and sends it to the
1773      * registered {@code ListSelectionListeners}.
1774      *
1775      * @param firstIndex the first index in the range, {@code <= lastIndex}
1776      * @param lastIndex the last index in the range, {@code >= firstIndex}
1777      * @param isAdjusting whether or not this is one in a series of
1778      *        multiple events, where changes are still being made
1779      *
1780      * @see #addListSelectionListener
1781      * @see #removeListSelectionListener
1782      * @see javax.swing.event.ListSelectionEvent
1783      * @see EventListenerList
1784      */
1785     protected void fireSelectionValueChanged(int firstIndex, int lastIndex,
1786                                              boolean isAdjusting)
1787     {
1788         Object[] listeners = listenerList.getListenerList();
1789         ListSelectionEvent e = null;
1790 
1791         for (int i = listeners.length - 2; i >= 0; i -= 2) {
1792             if (listeners[i] == ListSelectionListener.class) {
1793                 if (e == null) {
1794                     e = new ListSelectionEvent(this, firstIndex, lastIndex,
1795                                                isAdjusting);
1796                 }
1797                 ((ListSelectionListener)listeners[i+1]).valueChanged(e);
1798             }
1799         }
1800     }
1801 
1802 
1803     /* A ListSelectionListener that forwards ListSelectionEvents from
1804      * the selectionModel to the JList ListSelectionListeners.  The
1805      * forwarded events only differ from the originals in that their
1806      * source is the JList instead of the selectionModel itself.
1807      */
1808     private class ListSelectionHandler implements ListSelectionListener, Serializable
1809     {
1810         public void valueChanged(ListSelectionEvent e) {
1811             fireSelectionValueChanged(e.getFirstIndex(),
1812                                       e.getLastIndex(),
1813                                       e.getValueIsAdjusting());
1814         }
1815     }
1816 
1817 
1818     /**
1819      * Adds a listener to the list, to be notified each time a change to the
1820      * selection occurs; the preferred way of listening for selection state
1821      * changes. {@code JList} takes care of listening for selection state
1822      * changes in the selection model, and notifies the given listener of
1823      * each change. {@code ListSelectionEvent}s sent to the listener have a
1824      * {@code source} property set to this list.
1825      *
1826      * @param listener the {@code ListSelectionListener} to add
1827      * @see #getSelectionModel
1828      * @see #getListSelectionListeners
1829      */
1830     public void addListSelectionListener(ListSelectionListener listener)
1831     {
1832         if (selectionListener == null) {
1833             selectionListener = new ListSelectionHandler();
1834             getSelectionModel().addListSelectionListener(selectionListener);
1835         }
1836 
1837         listenerList.add(ListSelectionListener.class, listener);
1838     }
1839 
1840 
1841     /**
1842      * Removes a selection listener from the list.
1843      *
1844      * @param listener the {@code ListSelectionListener} to remove
1845      * @see #addListSelectionListener
1846      * @see #getSelectionModel
1847      */
1848     public void removeListSelectionListener(ListSelectionListener listener) {
1849         listenerList.remove(ListSelectionListener.class, listener);
1850     }
1851 
1852 
1853     /**
1854      * Returns an array of all the {@code ListSelectionListener}s added
1855      * to this {@code JList} by way of {@code addListSelectionListener}.
1856      *
1857      * @return all of the {@code ListSelectionListener}s on this list, or
1858      *         an empty array if no listeners have been added
1859      * @see #addListSelectionListener
1860      * @since 1.4
1861      */
1862     public ListSelectionListener[] getListSelectionListeners() {
1863         return listenerList.getListeners(ListSelectionListener.class);
1864     }
1865 
1866 
1867     /**
1868      * Sets the <code>selectionModel</code> for the list to a
1869      * non-<code>null</code> <code>ListSelectionModel</code>
1870      * implementation. The selection model handles the task of making single
1871      * selections, selections of contiguous ranges, and non-contiguous
1872      * selections.
1873      * <p>
1874      * This is a JavaBeans bound property.
1875      *
1876      * @param selectionModel  the <code>ListSelectionModel</code> that
1877      *                          implements the selections
1878      * @exception IllegalArgumentException   if <code>selectionModel</code>
1879      *                                          is <code>null</code>
1880      * @see #getSelectionModel
1881      * @beaninfo
1882      *       bound: true
1883      * description: The selection model, recording which cells are selected.
1884      */
1885     public void setSelectionModel(ListSelectionModel selectionModel) {
1886         if (selectionModel == null) {
1887             throw new IllegalArgumentException("selectionModel must be non null");
1888         }
1889 
1890         /* Remove the forwarding ListSelectionListener from the old
1891          * selectionModel, and add it to the new one, if necessary.
1892          */
1893         if (selectionListener != null) {
1894             this.selectionModel.removeListSelectionListener(selectionListener);
1895             selectionModel.addListSelectionListener(selectionListener);
1896         }
1897 
1898         ListSelectionModel oldValue = this.selectionModel;
1899         this.selectionModel = selectionModel;
1900         firePropertyChange("selectionModel", oldValue, selectionModel);
1901     }
1902 
1903 
1904     /**
1905      * Sets the selection mode for the list. This is a cover method that sets
1906      * the selection mode directly on the selection model.
1907      * <p>
1908      * The following list describes the accepted selection modes:
1909      * <ul>
1910      * <li>{@code ListSelectionModel.SINGLE_SELECTION} -
1911      *   Only one list index can be selected at a time. In this mode,
1912      *   {@code setSelectionInterval} and {@code addSelectionInterval} are
1913      *   equivalent, both replacing the current selection with the index
1914      *   represented by the second argument (the "lead").
1915      * <li>{@code ListSelectionModel.SINGLE_INTERVAL_SELECTION} -
1916      *   Only one contiguous interval can be selected at a time.
1917      *   In this mode, {@code addSelectionInterval} behaves like
1918      *   {@code setSelectionInterval} (replacing the current selection},
1919      *   unless the given interval is immediately adjacent to or overlaps
1920      *   the existing selection, and can be used to grow the selection.
1921      * <li>{@code ListSelectionModel.MULTIPLE_INTERVAL_SELECTION} -
1922      *   In this mode, there's no restriction on what can be selected.
1923      *   This mode is the default.
1924      * </ul>
1925      *
1926      * @param selectionMode the selection mode
1927      * @see #getSelectionMode
1928      * @throws IllegalArgumentException if the selection mode isn't
1929      *         one of those allowed
1930      * @beaninfo
1931      * description: The selection mode.
1932      *        enum: SINGLE_SELECTION            ListSelectionModel.SINGLE_SELECTION
1933      *              SINGLE_INTERVAL_SELECTION   ListSelectionModel.SINGLE_INTERVAL_SELECTION
1934      *              MULTIPLE_INTERVAL_SELECTION ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
1935      */
1936     public void setSelectionMode(int selectionMode) {
1937         getSelectionModel().setSelectionMode(selectionMode);
1938     }
1939 
1940     /**
1941      * Returns the current selection mode for the list. This is a cover
1942      * method that delegates to the method of the same name on the
1943      * list's selection model.
1944      *
1945      * @return the current selection mode
1946      * @see #setSelectionMode
1947      */
1948     public int getSelectionMode() {
1949         return getSelectionModel().getSelectionMode();
1950     }
1951 
1952 
1953     /**
1954      * Returns the anchor selection index. This is a cover method that
1955      * delegates to the method of the same name on the list's selection model.
1956      *
1957      * @return the anchor selection index
1958      * @see ListSelectionModel#getAnchorSelectionIndex
1959      */
1960     public int getAnchorSelectionIndex() {
1961         return getSelectionModel().getAnchorSelectionIndex();
1962     }
1963 
1964 
1965     /**
1966      * Returns the lead selection index. This is a cover method that
1967      * delegates to the method of the same name on the list's selection model.
1968      *
1969      * @return the lead selection index
1970      * @see ListSelectionModel#getLeadSelectionIndex
1971      * @beaninfo
1972      * description: The lead selection index.
1973      */
1974     public int getLeadSelectionIndex() {
1975         return getSelectionModel().getLeadSelectionIndex();
1976     }
1977 
1978 
1979     /**
1980      * Returns the smallest selected cell index, or {@code -1} if the selection
1981      * is empty. This is a cover method that delegates to the method of the same
1982      * name on the list's selection model.
1983      *
1984      * @return the smallest selected cell index, or {@code -1}
1985      * @see ListSelectionModel#getMinSelectionIndex
1986      */
1987     public int getMinSelectionIndex() {
1988         return getSelectionModel().getMinSelectionIndex();
1989     }
1990 
1991 
1992     /**
1993      * Returns the largest selected cell index, or {@code -1} if the selection
1994      * is empty. This is a cover method that delegates to the method of the same
1995      * name on the list's selection model.
1996      *
1997      * @return the largest selected cell index
1998      * @see ListSelectionModel#getMaxSelectionIndex
1999      */
2000     public int getMaxSelectionIndex() {
2001         return getSelectionModel().getMaxSelectionIndex();
2002     }
2003 
2004 
2005     /**
2006      * Returns {@code true} if the specified index is selected,
2007      * else {@code false}. This is a cover method that delegates to the method
2008      * of the same name on the list's selection model.
2009      *
2010      * @param index index to be queried for selection state
2011      * @return {@code true} if the specified index is selected,
2012      *         else {@code false}
2013      * @see ListSelectionModel#isSelectedIndex
2014      * @see #setSelectedIndex
2015      */
2016     public boolean isSelectedIndex(int index) {
2017         return getSelectionModel().isSelectedIndex(index);
2018     }
2019 
2020 
2021     /**
2022      * Returns {@code true} if nothing is selected, else {@code false}.
2023      * This is a cover method that delegates to the method of the same
2024      * name on the list's selection model.
2025      *
2026      * @return {@code true} if nothing is selected, else {@code false}
2027      * @see ListSelectionModel#isSelectionEmpty
2028      * @see #clearSelection
2029      */
2030     public boolean isSelectionEmpty() {
2031         return getSelectionModel().isSelectionEmpty();
2032     }
2033 
2034 
2035     /**
2036      * Clears the selection; after calling this method, {@code isSelectionEmpty}
2037      * will return {@code true}. This is a cover method that delegates to the
2038      * method of the same name on the list's selection model.
2039      *
2040      * @see ListSelectionModel#clearSelection
2041      * @see #isSelectionEmpty
2042      */
2043     public void clearSelection() {
2044         getSelectionModel().clearSelection();
2045     }
2046 
2047 
2048     /**
2049      * Selects the specified interval. Both {@code anchor} and {@code lead}
2050      * indices are included. {@code anchor} doesn't have to be less than or
2051      * equal to {@code lead}. This is a cover method that delegates to the
2052      * method of the same name on the list's selection model.
2053      * <p>
2054      * Refer to the documentation of the selection model class being used
2055      * for details on how values less than {@code 0} are handled.
2056      *
2057      * @param anchor the first index to select
2058      * @param lead the last index to select
2059      * @see ListSelectionModel#setSelectionInterval
2060      * @see DefaultListSelectionModel#setSelectionInterval
2061      * @see #createSelectionModel
2062      * @see #addSelectionInterval
2063      * @see #removeSelectionInterval
2064      */
2065     public void setSelectionInterval(int anchor, int lead) {
2066         getSelectionModel().setSelectionInterval(anchor, lead);
2067     }
2068 
2069 
2070     /**
2071      * Sets the selection to be the union of the specified interval with current
2072      * selection. Both the {@code anchor} and {@code lead} indices are
2073      * included. {@code anchor} doesn't have to be less than or
2074      * equal to {@code lead}. This is a cover method that delegates to the
2075      * method of the same name on the list's selection model.
2076      * <p>
2077      * Refer to the documentation of the selection model class being used
2078      * for details on how values less than {@code 0} are handled.
2079      *
2080      * @param anchor the first index to add to the selection
2081      * @param lead the last index to add to the selection
2082      * @see ListSelectionModel#addSelectionInterval
2083      * @see DefaultListSelectionModel#addSelectionInterval
2084      * @see #createSelectionModel
2085      * @see #setSelectionInterval
2086      * @see #removeSelectionInterval
2087      */
2088     public void addSelectionInterval(int anchor, int lead) {
2089         getSelectionModel().addSelectionInterval(anchor, lead);
2090     }
2091 
2092 
2093     /**
2094      * Sets the selection to be the set difference of the specified interval
2095      * and the current selection. Both the {@code index0} and {@code index1}
2096      * indices are removed. {@code index0} doesn't have to be less than or
2097      * equal to {@code index1}. This is a cover method that delegates to the
2098      * method of the same name on the list's selection model.
2099      * <p>
2100      * Refer to the documentation of the selection model class being used
2101      * for details on how values less than {@code 0} are handled.
2102      *
2103      * @param index0 the first index to remove from the selection
2104      * @param index1 the last index to remove from the selection
2105      * @see ListSelectionModel#removeSelectionInterval
2106      * @see DefaultListSelectionModel#removeSelectionInterval
2107      * @see #createSelectionModel
2108      * @see #setSelectionInterval
2109      * @see #addSelectionInterval
2110      */
2111     public void removeSelectionInterval(int index0, int index1) {
2112         getSelectionModel().removeSelectionInterval(index0, index1);
2113     }
2114 
2115 
2116     /**
2117      * Sets the selection model's {@code valueIsAdjusting} property. When
2118      * {@code true}, upcoming changes to selection should be considered part
2119      * of a single change. This property is used internally and developers
2120      * typically need not call this method. For example, when the model is being
2121      * updated in response to a user drag, the value of the property is set
2122      * to {@code true} when the drag is initiated and set to {@code false}
2123      * when the drag is finished. This allows listeners to update only
2124      * when a change has been finalized, rather than handling all of the
2125      * intermediate values.
2126      * <p>
2127      * You may want to use this directly if making a series of changes
2128      * that should be considered part of a single change.
2129      * <p>
2130      * This is a cover method that delegates to the method of the same name on
2131      * the list's selection model. See the documentation for
2132      * {@link javax.swing.ListSelectionModel#setValueIsAdjusting} for
2133      * more details.
2134      *
2135      * @param b the new value for the property
2136      * @see ListSelectionModel#setValueIsAdjusting
2137      * @see javax.swing.event.ListSelectionEvent#getValueIsAdjusting
2138      * @see #getValueIsAdjusting
2139      */
2140     public void setValueIsAdjusting(boolean b) {
2141         getSelectionModel().setValueIsAdjusting(b);
2142     }
2143 
2144 
2145     /**
2146      * Returns the value of the selection model's {@code isAdjusting} property.
2147      * <p>
2148      * This is a cover method that delegates to the method of the same name on
2149      * the list's selection model.
2150      *
2151      * @return the value of the selection model's {@code isAdjusting} property.
2152      *
2153      * @see #setValueIsAdjusting
2154      * @see ListSelectionModel#getValueIsAdjusting
2155      */
2156     public boolean getValueIsAdjusting() {
2157         return getSelectionModel().getValueIsAdjusting();
2158     }
2159 
2160 
2161     /**
2162      * Returns an array of all of the selected indices, in increasing
2163      * order.
2164      *
2165      * @return all of the selected indices, in increasing order,
2166      *         or an empty array if nothing is selected
2167      * @see #removeSelectionInterval
2168      * @see #addListSelectionListener
2169      */
2170     @Transient
2171     public int[] getSelectedIndices() {
2172         ListSelectionModel sm = getSelectionModel();
2173         int iMin = sm.getMinSelectionIndex();
2174         int iMax = sm.getMaxSelectionIndex();
2175 
2176         if ((iMin < 0) || (iMax < 0)) {
2177             return new int[0];
2178         }
2179 
2180         int[] rvTmp = new int[1+ (iMax - iMin)];
2181         int n = 0;
2182         for(int i = iMin; i <= iMax; i++) {
2183             if (sm.isSelectedIndex(i)) {
2184                 rvTmp[n++] = i;
2185             }
2186         }
2187         int[] rv = new int[n];
2188         System.arraycopy(rvTmp, 0, rv, 0, n);
2189         return rv;
2190     }
2191 
2192 
2193     /**
2194      * Selects a single cell. Does nothing if the given index is greater
2195      * than or equal to the model size. This is a convenience method that uses
2196      * {@code setSelectionInterval} on the selection model. Refer to the
2197      * documentation for the selection model class being used for details on
2198      * how values less than {@code 0} are handled.
2199      *
2200      * @param index the index of the cell to select
2201      * @see ListSelectionModel#setSelectionInterval
2202      * @see #isSelectedIndex
2203      * @see #addListSelectionListener
2204      * @beaninfo
2205      * description: The index of the selected cell.
2206      */
2207     public void setSelectedIndex(int index) {
2208         if (index >= getModel().getSize()) {
2209             return;
2210         }
2211         getSelectionModel().setSelectionInterval(index, index);
2212     }
2213 
2214 
2215     /**
2216      * Changes the selection to be the set of indices specified by the given
2217      * array. Indices greater than or equal to the model size are ignored.
2218      * This is a convenience method that clears the selection and then uses
2219      * {@code addSelectionInterval} on the selection model to add the indices.
2220      * Refer to the documentation of the selection model class being used for
2221      * details on how values less than {@code 0} are handled.
2222      *
2223      * @param indices an array of the indices of the cells to select,
2224      *                {@code non-null}
2225      * @see ListSelectionModel#addSelectionInterval
2226      * @see #isSelectedIndex
2227      * @see #addListSelectionListener
2228      * @throws NullPointerException if the given array is {@code null}
2229      */
2230     public void setSelectedIndices(int[] indices) {
2231         ListSelectionModel sm = getSelectionModel();
2232         sm.clearSelection();
2233         int size = getModel().getSize();
2234         for (int i : indices) {
2235             if (i < size) {
2236                 sm.addSelectionInterval(i, i);
2237             }
2238         }
2239     }
2240 
2241 
2242     /**
2243      * Returns an array of all the selected values, in increasing order based
2244      * on their indices in the list.
2245      *
2246      * @return the selected values, or an empty array if nothing is selected
2247      * @see #isSelectedIndex
2248      * @see #getModel
2249      * @see #addListSelectionListener
2250      *
2251      * @deprecated As of JDK 1.7, replaced by {@link #getSelectedValuesList()}
2252      */
2253     @Deprecated
2254     public Object[] getSelectedValues() {
2255         ListSelectionModel sm = getSelectionModel();
2256         ListModel<E> dm = getModel();
2257 
2258         int iMin = sm.getMinSelectionIndex();
2259         int iMax = sm.getMaxSelectionIndex();
2260 
2261         if ((iMin < 0) || (iMax < 0)) {
2262             return new Object[0];
2263         }
2264 
2265         Object[] rvTmp = new Object[1+ (iMax - iMin)];
2266         int n = 0;
2267         for(int i = iMin; i <= iMax; i++) {
2268             if (sm.isSelectedIndex(i)) {
2269                 rvTmp[n++] = dm.getElementAt(i);
2270             }
2271         }
2272         Object[] rv = new Object[n];
2273         System.arraycopy(rvTmp, 0, rv, 0, n);
2274         return rv;
2275     }
2276 
2277     /**
2278      * Returns a list of all the selected items, in increasing order based
2279      * on their indices in the list.
2280      *
2281      * @return the selected items, or an empty list if nothing is selected
2282      * @see #isSelectedIndex
2283      * @see #getModel
2284      * @see #addListSelectionListener
2285      *
2286      * @since 1.7
2287      */
2288     public List<E> getSelectedValuesList() {
2289         ListSelectionModel sm = getSelectionModel();
2290         ListModel<E> dm = getModel();
2291 
2292         int iMin = sm.getMinSelectionIndex();
2293         int iMax = sm.getMaxSelectionIndex();
2294 
2295         if ((iMin < 0) || (iMax < 0)) {
2296             return Collections.emptyList();
2297         }
2298 
2299         List<E> selectedItems = new ArrayList<E>();
2300         for(int i = iMin; i <= iMax; i++) {
2301             if (sm.isSelectedIndex(i)) {
2302                 selectedItems.add(dm.getElementAt(i));
2303             }
2304         }
2305         return selectedItems;
2306     }
2307 
2308 
2309     /**
2310      * Returns the smallest selected cell index; <i>the selection</i> when only
2311      * a single item is selected in the list. When multiple items are selected,
2312      * it is simply the smallest selected index. Returns {@code -1} if there is
2313      * no selection.
2314      * <p>
2315      * This method is a cover that delegates to {@code getMinSelectionIndex}.
2316      *
2317      * @return the smallest selected cell index
2318      * @see #getMinSelectionIndex
2319      * @see #addListSelectionListener
2320      */
2321     public int getSelectedIndex() {
2322         return getMinSelectionIndex();
2323     }
2324 
2325 
2326     /**
2327      * Returns the value for the smallest selected cell index;
2328      * <i>the selected value</i> when only a single item is selected in the
2329      * list. When multiple items are selected, it is simply the value for the
2330      * smallest selected index. Returns {@code null} if there is no selection.
2331      * <p>
2332      * This is a convenience method that simply returns the model value for
2333      * {@code getMinSelectionIndex}.
2334      *
2335      * @return the first selected value
2336      * @see #getMinSelectionIndex
2337      * @see #getModel
2338      * @see #addListSelectionListener
2339      */
2340     public E getSelectedValue() {
2341         int i = getMinSelectionIndex();
2342         return (i == -1) ? null : getModel().getElementAt(i);
2343     }
2344 
2345 
2346     /**
2347      * Selects the specified object from the list.
2348      *
2349      * @param anObject      the object to select
2350      * @param shouldScroll  {@code true} if the list should scroll to display
2351      *                      the selected object, if one exists; otherwise {@code false}
2352      */
2353     public void setSelectedValue(Object anObject,boolean shouldScroll) {
2354         if(anObject == null)
2355             setSelectedIndex(-1);
2356         else if(!anObject.equals(getSelectedValue())) {
2357             int i,c;
2358             ListModel<E> dm = getModel();
2359             for(i=0,c=dm.getSize();i<c;i++)
2360                 if(anObject.equals(dm.getElementAt(i))){
2361                     setSelectedIndex(i);
2362                     if(shouldScroll)
2363                         ensureIndexIsVisible(i);
2364                     repaint();  /** FIX-ME setSelectedIndex does not redraw all the time with the basic l&f**/
2365                     return;
2366                 }
2367             setSelectedIndex(-1);
2368         }
2369         repaint(); /** FIX-ME setSelectedIndex does not redraw all the time with the basic l&f**/
2370     }
2371 
2372 
2373 
2374     /**
2375      * --- The Scrollable Implementation ---
2376      */
2377 
2378     private void checkScrollableParameters(Rectangle visibleRect, int orientation) {
2379         if (visibleRect == null) {
2380             throw new IllegalArgumentException("visibleRect must be non-null");
2381         }
2382         switch (orientation) {
2383         case SwingConstants.VERTICAL:
2384         case SwingConstants.HORIZONTAL:
2385             break;
2386         default:
2387             throw new IllegalArgumentException("orientation must be one of: VERTICAL, HORIZONTAL");
2388         }
2389     }
2390 
2391 
2392     /**
2393      * Computes the size of viewport needed to display {@code visibleRowCount}
2394      * rows. The value returned by this method depends on the layout
2395      * orientation:
2396      * <p>
2397      * <b>{@code VERTICAL}:</b>
2398      * <br>
2399      * This is trivial if both {@code fixedCellWidth} and {@code fixedCellHeight}
2400      * have been set (either explicitly or by specifying a prototype cell value).
2401      * The width is simply the {@code fixedCellWidth} plus the list's horizontal
2402      * insets. The height is the {@code fixedCellHeight} multiplied by the
2403      * {@code visibleRowCount}, plus the list's vertical insets.
2404      * <p>
2405      * If either {@code fixedCellWidth} or {@code fixedCellHeight} haven't been
2406      * specified, heuristics are used. If the model is empty, the width is
2407      * the {@code fixedCellWidth}, if greater than {@code 0}, or a hard-coded
2408      * value of {@code 256}. The height is the {@code fixedCellHeight} multiplied
2409      * by {@code visibleRowCount}, if {@code fixedCellHeight} is greater than
2410      * {@code 0}, otherwise it is a hard-coded value of {@code 16} multiplied by
2411      * {@code visibleRowCount}.
2412      * <p>
2413      * If the model isn't empty, the width is the preferred size's width,
2414      * typically the width of the widest list element. The height is the
2415      * {@code fixedCellHeight} multiplied by the {@code visibleRowCount},
2416      * plus the list's vertical insets.
2417      * <p>
2418      * <b>{@code VERTICAL_WRAP} or {@code HORIZONTAL_WRAP}:</b>
2419      * <br>
2420      * This method simply returns the value from {@code getPreferredSize}.
2421      * The list's {@code ListUI} is expected to override {@code getPreferredSize}
2422      * to return an appropriate value.
2423      *
2424      * @return a dimension containing the size of the viewport needed
2425      *          to display {@code visibleRowCount} rows
2426      * @see #getPreferredScrollableViewportSize
2427      * @see #setPrototypeCellValue
2428      */
2429     public Dimension getPreferredScrollableViewportSize()
2430     {
2431         if (getLayoutOrientation() != VERTICAL) {
2432             return getPreferredSize();
2433         }
2434         Insets insets = getInsets();
2435         int dx = insets.left + insets.right;
2436         int dy = insets.top + insets.bottom;
2437 
2438         int visibleRowCount = getVisibleRowCount();
2439         int fixedCellWidth = getFixedCellWidth();
2440         int fixedCellHeight = getFixedCellHeight();
2441 
2442         if ((fixedCellWidth > 0) && (fixedCellHeight > 0)) {
2443             int width = fixedCellWidth + dx;
2444             int height = (visibleRowCount * fixedCellHeight) + dy;
2445             return new Dimension(width, height);
2446         }
2447         else if (getModel().getSize() > 0) {
2448             int width = getPreferredSize().width;
2449             int height;
2450             Rectangle r = getCellBounds(0, 0);
2451             if (r != null) {
2452                 height = (visibleRowCount * r.height) + dy;
2453             }
2454             else {
2455                 // Will only happen if UI null, shouldn't matter what we return
2456                 height = 1;
2457             }
2458             return new Dimension(width, height);
2459         }
2460         else {
2461             fixedCellWidth = (fixedCellWidth > 0) ? fixedCellWidth : 256;
2462             fixedCellHeight = (fixedCellHeight > 0) ? fixedCellHeight : 16;
2463             return new Dimension(fixedCellWidth, fixedCellHeight * visibleRowCount);
2464         }
2465     }
2466 
2467 
2468     /**
2469      * Returns the distance to scroll to expose the next or previous
2470      * row (for vertical scrolling) or column (for horizontal scrolling).
2471      * <p>
2472      * For horizontal scrolling, if the layout orientation is {@code VERTICAL},
2473      * then the list's font size is returned (or {@code 1} if the font is
2474      * {@code null}).
2475      *
2476      * @param visibleRect the view area visible within the viewport
2477      * @param orientation {@code SwingConstants.HORIZONTAL} or
2478      *                    {@code SwingConstants.VERTICAL}
2479      * @param direction less or equal to zero to scroll up/back,
2480      *                  greater than zero for down/forward
2481      * @return the "unit" increment for scrolling in the specified direction;
2482      *         always positive
2483      * @see #getScrollableBlockIncrement
2484      * @see Scrollable#getScrollableUnitIncrement
2485      * @throws IllegalArgumentException if {@code visibleRect} is {@code null}, or
2486      *         {@code orientation} isn't one of {@code SwingConstants.VERTICAL} or
2487      *         {@code SwingConstants.HORIZONTAL}
2488      */
2489     public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
2490     {
2491         checkScrollableParameters(visibleRect, orientation);
2492 
2493         if (orientation == SwingConstants.VERTICAL) {
2494             int row = locationToIndex(visibleRect.getLocation());
2495 
2496             if (row == -1) {
2497                 return 0;
2498             }
2499             else {
2500                 /* Scroll Down */
2501                 if (direction > 0) {
2502                     Rectangle r = getCellBounds(row, row);
2503                     return (r == null) ? 0 : r.height - (visibleRect.y - r.y);
2504                 }
2505                 /* Scroll Up */
2506                 else {
2507                     Rectangle r = getCellBounds(row, row);
2508 
2509                     /* The first row is completely visible and it's row 0.
2510                      * We're done.
2511                      */
2512                     if ((r.y == visibleRect.y) && (row == 0))  {
2513                         return 0;
2514                     }
2515                     /* The first row is completely visible, return the
2516                      * height of the previous row or 0 if the first row
2517                      * is the top row of the list.
2518                      */
2519                     else if (r.y == visibleRect.y) {
2520                         Point loc = r.getLocation();
2521                         loc.y--;
2522                         int prevIndex = locationToIndex(loc);
2523                         Rectangle prevR = getCellBounds(prevIndex, prevIndex);
2524 
2525                         if (prevR == null || prevR.y >= r.y) {
2526                             return 0;
2527                         }
2528                         return prevR.height;
2529                     }
2530                     /* The first row is partially visible, return the
2531                      * height of hidden part.
2532                      */
2533                     else {
2534                         return visibleRect.y - r.y;
2535                     }
2536                 }
2537             }
2538         } else if (orientation == SwingConstants.HORIZONTAL &&
2539                            getLayoutOrientation() != JList.VERTICAL) {
2540             boolean leftToRight = getComponentOrientation().isLeftToRight();
2541             int index;
2542             Point leadingPoint;
2543 
2544             if (leftToRight) {
2545                 leadingPoint = visibleRect.getLocation();
2546             }
2547             else {
2548                 leadingPoint = new Point(visibleRect.x + visibleRect.width -1,
2549                                          visibleRect.y);
2550             }
2551             index = locationToIndex(leadingPoint);
2552 
2553             if (index != -1) {
2554                 Rectangle cellBounds = getCellBounds(index, index);
2555                 if (cellBounds != null && cellBounds.contains(leadingPoint)) {
2556                     int leadingVisibleEdge;
2557                     int leadingCellEdge;
2558 
2559                     if (leftToRight) {
2560                         leadingVisibleEdge = visibleRect.x;
2561                         leadingCellEdge = cellBounds.x;
2562                     }
2563                     else {
2564                         leadingVisibleEdge = visibleRect.x + visibleRect.width;
2565                         leadingCellEdge = cellBounds.x + cellBounds.width;
2566                     }
2567 
2568                     if (leadingCellEdge != leadingVisibleEdge) {
2569                         if (direction < 0) {
2570                             // Show remainder of leading cell
2571                             return Math.abs(leadingVisibleEdge - leadingCellEdge);
2572 
2573                         }
2574                         else if (leftToRight) {
2575                             // Hide rest of leading cell
2576                             return leadingCellEdge + cellBounds.width - leadingVisibleEdge;
2577                         }
2578                         else {
2579                             // Hide rest of leading cell
2580                             return leadingVisibleEdge - cellBounds.x;
2581                         }
2582                     }
2583                     // ASSUME: All cells are the same width
2584                     return cellBounds.width;
2585                 }
2586             }
2587         }
2588         Font f = getFont();
2589         return (f != null) ? f.getSize() : 1;
2590     }
2591 
2592 
2593     /**
2594      * Returns the distance to scroll to expose the next or previous block.
2595      * <p>
2596      * For vertical scrolling, the following rules are used:
2597      * <ul>
2598      * <li>if scrolling down, returns the distance to scroll so that the last
2599      * visible element becomes the first completely visible element
2600      * <li>if scrolling up, returns the distance to scroll so that the first
2601      * visible element becomes the last completely visible element
2602      * <li>returns {@code visibleRect.height} if the list is empty
2603      * </ul>
2604      * <p>
2605      * For horizontal scrolling, when the layout orientation is either
2606      * {@code VERTICAL_WRAP} or {@code HORIZONTAL_WRAP}:
2607      * <ul>
2608      * <li>if scrolling right, returns the distance to scroll so that the
2609      * last visible element becomes
2610      * the first completely visible element
2611      * <li>if scrolling left, returns the distance to scroll so that the first
2612      * visible element becomes the last completely visible element
2613      * <li>returns {@code visibleRect.width} if the list is empty
2614      * </ul>
2615      * <p>
2616      * For horizontal scrolling and {@code VERTICAL} orientation,
2617      * returns {@code visibleRect.width}.
2618      * <p>
2619      * Note that the value of {@code visibleRect} must be the equal to
2620      * {@code this.getVisibleRect()}.
2621      *
2622      * @param visibleRect the view area visible within the viewport
2623      * @param orientation {@code SwingConstants.HORIZONTAL} or
2624      *                    {@code SwingConstants.VERTICAL}
2625      * @param direction less or equal to zero to scroll up/back,
2626      *                  greater than zero for down/forward
2627      * @return the "block" increment for scrolling in the specified direction;
2628      *         always positive
2629      * @see #getScrollableUnitIncrement
2630      * @see Scrollable#getScrollableBlockIncrement
2631      * @throws IllegalArgumentException if {@code visibleRect} is {@code null}, or
2632      *         {@code orientation} isn't one of {@code SwingConstants.VERTICAL} or
2633      *         {@code SwingConstants.HORIZONTAL}
2634      */
2635     public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
2636         checkScrollableParameters(visibleRect, orientation);
2637         if (orientation == SwingConstants.VERTICAL) {
2638             int inc = visibleRect.height;
2639             /* Scroll Down */
2640             if (direction > 0) {
2641                 // last cell is the lowest left cell
2642                 int last = locationToIndex(new Point(visibleRect.x, visibleRect.y+visibleRect.height-1));
2643                 if (last != -1) {
2644                     Rectangle lastRect = getCellBounds(last,last);
2645                     if (lastRect != null) {
2646                         inc = lastRect.y - visibleRect.y;
2647                         if ( (inc == 0) && (last < getModel().getSize()-1) ) {
2648                             inc = lastRect.height;
2649                         }
2650                     }
2651                 }
2652             }
2653             /* Scroll Up */
2654             else {
2655                 int newFirst = locationToIndex(new Point(visibleRect.x, visibleRect.y-visibleRect.height));
2656                 int first = getFirstVisibleIndex();
2657                 if (newFirst != -1) {
2658                     if (first == -1) {
2659                         first = locationToIndex(visibleRect.getLocation());
2660                     }
2661                     Rectangle newFirstRect = getCellBounds(newFirst,newFirst);
2662                     Rectangle firstRect = getCellBounds(first,first);
2663                     if ((newFirstRect != null) && (firstRect!=null)) {
2664                         while ( (newFirstRect.y + visibleRect.height <
2665                                  firstRect.y + firstRect.height) &&
2666                                 (newFirstRect.y < firstRect.y) ) {
2667                             newFirst++;
2668                             newFirstRect = getCellBounds(newFirst,newFirst);
2669                         }
2670                         inc = visibleRect.y - newFirstRect.y;
2671                         if ( (inc <= 0) && (newFirstRect.y > 0)) {
2672                             newFirst--;
2673                             newFirstRect = getCellBounds(newFirst,newFirst);
2674                             if (newFirstRect != null) {
2675                                 inc = visibleRect.y - newFirstRect.y;
2676                             }
2677                         }
2678                     }
2679                 }
2680             }
2681             return inc;
2682         }
2683         else if (orientation == SwingConstants.HORIZONTAL &&
2684                  getLayoutOrientation() != JList.VERTICAL) {
2685             boolean leftToRight = getComponentOrientation().isLeftToRight();
2686             int inc = visibleRect.width;
2687             /* Scroll Right (in ltr mode) or Scroll Left (in rtl mode) */
2688             if (direction > 0) {
2689                 // position is upper right if ltr, or upper left otherwise
2690                 int x = visibleRect.x + (leftToRight ? (visibleRect.width - 1) : 0);
2691                 int last = locationToIndex(new Point(x, visibleRect.y));
2692 
2693                 if (last != -1) {
2694                     Rectangle lastRect = getCellBounds(last,last);
2695                     if (lastRect != null) {
2696                         if (leftToRight) {
2697                             inc = lastRect.x - visibleRect.x;
2698                         } else {
2699                             inc = visibleRect.x + visibleRect.width
2700                                       - (lastRect.x + lastRect.width);
2701                         }
2702                         if (inc < 0) {
2703                             inc += lastRect.width;
2704                         } else if ( (inc == 0) && (last < getModel().getSize()-1) ) {
2705                             inc = lastRect.width;
2706                         }
2707                     }
2708                 }
2709             }
2710             /* Scroll Left (in ltr mode) or Scroll Right (in rtl mode) */
2711             else {
2712                 // position is upper left corner of the visibleRect shifted
2713                 // left by the visibleRect.width if ltr, or upper right shifted
2714                 // right by the visibleRect.width otherwise
2715                 int x = visibleRect.x + (leftToRight
2716                                          ? -visibleRect.width
2717                                          : visibleRect.width - 1 + visibleRect.width);
2718                 int first = locationToIndex(new Point(x, visibleRect.y));
2719 
2720                 if (first != -1) {
2721                     Rectangle firstRect = getCellBounds(first,first);
2722                     if (firstRect != null) {
2723                         // the right of the first cell
2724                         int firstRight = firstRect.x + firstRect.width;
2725 
2726                         if (leftToRight) {
2727                             if ((firstRect.x < visibleRect.x - visibleRect.width)
2728                                     && (firstRight < visibleRect.x)) {
2729                                 inc = visibleRect.x - firstRight;
2730                             } else {
2731                                 inc = visibleRect.x - firstRect.x;
2732                             }
2733                         } else {
2734                             int visibleRight = visibleRect.x + visibleRect.width;
2735 
2736                             if ((firstRight > visibleRight + visibleRect.width)
2737                                     && (firstRect.x > visibleRight)) {
2738                                 inc = firstRect.x - visibleRight;
2739                             } else {
2740                                 inc = firstRight - visibleRight;
2741                             }
2742                         }
2743                     }
2744                 }
2745             }
2746             return inc;
2747         }
2748         return visibleRect.width;
2749     }
2750 
2751 
2752     /**
2753      * Returns {@code true} if this {@code JList} is displayed in a
2754      * {@code JViewport} and the viewport is wider than the list's
2755      * preferred width, or if the layout orientation is {@code HORIZONTAL_WRAP}
2756      * and {@code visibleRowCount <= 0}; otherwise returns {@code false}.
2757      * <p>
2758      * If {@code false}, then don't track the viewport's width. This allows
2759      * horizontal scrolling if the {@code JViewport} is itself embedded in a
2760      * {@code JScrollPane}.
2761      *
2762      * @return whether or not an enclosing viewport should force the list's
2763      *         width to match its own
2764      * @see Scrollable#getScrollableTracksViewportWidth
2765      */
2766     public boolean getScrollableTracksViewportWidth() {
2767         if (getLayoutOrientation() == HORIZONTAL_WRAP &&
2768                                       getVisibleRowCount() <= 0) {
2769             return true;
2770         }
2771         Container parent = SwingUtilities.getUnwrappedParent(this);
2772         if (parent instanceof JViewport) {
2773             return parent.getWidth() > getPreferredSize().width;
2774         }
2775         return false;
2776     }
2777 
2778     /**
2779      * Returns {@code true} if this {@code JList} is displayed in a
2780      * {@code JViewport} and the viewport is taller than the list's
2781      * preferred height, or if the layout orientation is {@code VERTICAL_WRAP}
2782      * and {@code visibleRowCount <= 0}; otherwise returns {@code false}.
2783      * <p>
2784      * If {@code false}, then don't track the viewport's height. This allows
2785      * vertical scrolling if the {@code JViewport} is itself embedded in a
2786      * {@code JScrollPane}.
2787      *
2788      * @return whether or not an enclosing viewport should force the list's
2789      *         height to match its own
2790      * @see Scrollable#getScrollableTracksViewportHeight
2791      */
2792     public boolean getScrollableTracksViewportHeight() {
2793         if (getLayoutOrientation() == VERTICAL_WRAP &&
2794                      getVisibleRowCount() <= 0) {
2795             return true;
2796         }
2797         Container parent = SwingUtilities.getUnwrappedParent(this);
2798         if (parent instanceof JViewport) {
2799             return parent.getHeight() > getPreferredSize().height;
2800         }
2801         return false;
2802     }
2803 
2804 
2805     /*
2806      * See {@code readObject} and {@code writeObject} in {@code JComponent}
2807      * for more information about serialization in Swing.
2808      */
2809     private void writeObject(ObjectOutputStream s) throws IOException {
2810         s.defaultWriteObject();
2811         if (getUIClassID().equals(uiClassID)) {
2812             byte count = JComponent.getWriteObjCounter(this);
2813             JComponent.setWriteObjCounter(this, --count);
2814             if (count == 0 && ui != null) {
2815                 ui.installUI(this);
2816             }
2817         }
2818     }
2819 
2820 
2821     /**
2822      * Returns a {@code String} representation of this {@code JList}.
2823      * This method is intended to be used only for debugging purposes,
2824      * and the content and format of the returned {@code String} may vary
2825      * between implementations. The returned {@code String} may be empty,
2826      * but may not be {@code null}.
2827      *
2828      * @return  a {@code String} representation of this {@code JList}.
2829      */
2830     protected String paramString() {
2831         String selectionForegroundString = (selectionForeground != null ?
2832                                             selectionForeground.toString() :
2833                                             "");
2834         String selectionBackgroundString = (selectionBackground != null ?
2835                                             selectionBackground.toString() :
2836                                             "");
2837 
2838         return super.paramString() +
2839         ",fixedCellHeight=" + fixedCellHeight +
2840         ",fixedCellWidth=" + fixedCellWidth +
2841         ",horizontalScrollIncrement=" + horizontalScrollIncrement +
2842         ",selectionBackground=" + selectionBackgroundString +
2843         ",selectionForeground=" + selectionForegroundString +
2844         ",visibleRowCount=" + visibleRowCount +
2845         ",layoutOrientation=" + layoutOrientation;
2846     }
2847 
2848 
2849     /**
2850      * --- Accessibility Support ---
2851      */
2852 
2853     /**
2854      * Gets the {@code AccessibleContext} associated with this {@code JList}.
2855      * For {@code JList}, the {@code AccessibleContext} takes the form of an
2856      * {@code AccessibleJList}.
2857      * <p>
2858      * A new {@code AccessibleJList} instance is created if necessary.
2859      *
2860      * @return an {@code AccessibleJList} that serves as the
2861      *         {@code AccessibleContext} of this {@code JList}
2862      */
2863     public AccessibleContext getAccessibleContext() {
2864         if (accessibleContext == null) {
2865             accessibleContext = new AccessibleJList();
2866         }
2867         return accessibleContext;
2868     }
2869 
2870     /**
2871      * This class implements accessibility support for the
2872      * {@code JList} class. It provides an implementation of the
2873      * Java Accessibility API appropriate to list user-interface
2874      * elements.
2875      * <p>
2876      * <strong>Warning:</strong>
2877      * Serialized objects of this class will not be compatible with
2878      * future Swing releases. The current serialization support is
2879      * appropriate for short term storage or RMI between applications running
2880      * the same version of Swing.  As of 1.4, support for long term storage
2881      * of all JavaBeans&trade;
2882      * has been added to the <code>java.beans</code> package.
2883      * Please see {@link java.beans.XMLEncoder}.
2884      */
2885     @SuppressWarnings("serial") // Same-version serialization only
2886     protected class AccessibleJList extends AccessibleJComponent
2887         implements AccessibleSelection, PropertyChangeListener,
2888         ListSelectionListener, ListDataListener {
2889 
2890         int leadSelectionIndex;
2891 
2892         public AccessibleJList() {
2893             super();
2894             JList.this.addPropertyChangeListener(this);
2895             JList.this.getSelectionModel().addListSelectionListener(this);
2896             JList.this.getModel().addListDataListener(this);
2897             leadSelectionIndex = JList.this.getLeadSelectionIndex();
2898         }
2899 
2900         /**
2901          * Property Change Listener change method. Used to track changes
2902          * to the DataModel and ListSelectionModel, in order to re-set
2903          * listeners to those for reporting changes there via the Accessibility
2904          * PropertyChange mechanism.
2905          *
2906          * @param e PropertyChangeEvent
2907          */
2908         public void propertyChange(PropertyChangeEvent e) {
2909             String name = e.getPropertyName();
2910             Object oldValue = e.getOldValue();
2911             Object newValue = e.getNewValue();
2912 
2913                 // re-set listData listeners
2914             if (name.compareTo("model") == 0) {
2915 
2916                 if (oldValue != null && oldValue instanceof ListModel) {
2917                     ((ListModel) oldValue).removeListDataListener(this);
2918                 }
2919                 if (newValue != null && newValue instanceof ListModel) {
2920                     ((ListModel) newValue).addListDataListener(this);
2921                 }
2922 
2923                 // re-set listSelectionModel listeners
2924             } else if (name.compareTo("selectionModel") == 0) {
2925 
2926                 if (oldValue != null && oldValue instanceof ListSelectionModel) {
2927                     ((ListSelectionModel) oldValue).removeListSelectionListener(this);
2928                 }
2929                 if (newValue != null && newValue instanceof ListSelectionModel) {
2930                     ((ListSelectionModel) newValue).addListSelectionListener(this);
2931                 }
2932 
2933                 firePropertyChange(
2934                     AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
2935                     Boolean.valueOf(false), Boolean.valueOf(true));
2936             }
2937         }
2938 
2939         /**
2940          * List Selection Listener value change method. Used to fire
2941          * the property change
2942          *
2943          * @param e ListSelectionEvent
2944          *
2945          */
2946         public void valueChanged(ListSelectionEvent e) {
2947             int oldLeadSelectionIndex = leadSelectionIndex;
2948             leadSelectionIndex = JList.this.getLeadSelectionIndex();
2949             if (oldLeadSelectionIndex != leadSelectionIndex) {
2950                 Accessible oldLS, newLS;
2951                 oldLS = (oldLeadSelectionIndex >= 0)
2952                         ? getAccessibleChild(oldLeadSelectionIndex)
2953                         : null;
2954                 newLS = (leadSelectionIndex >= 0)
2955                         ? getAccessibleChild(leadSelectionIndex)
2956                         : null;
2957                 firePropertyChange(AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY,
2958                                    oldLS, newLS);
2959             }
2960 
2961             firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
2962                                Boolean.valueOf(false), Boolean.valueOf(true));
2963             firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
2964                                Boolean.valueOf(false), Boolean.valueOf(true));
2965 
2966             // Process the State changes for Multiselectable
2967             AccessibleStateSet s = getAccessibleStateSet();
2968             ListSelectionModel lsm = JList.this.getSelectionModel();
2969             if (lsm.getSelectionMode() != ListSelectionModel.SINGLE_SELECTION) {
2970                 if (!s.contains(AccessibleState.MULTISELECTABLE)) {
2971                     s.add(AccessibleState.MULTISELECTABLE);
2972                     firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
2973                                        null, AccessibleState.MULTISELECTABLE);
2974                 }
2975             } else {
2976                 if (s.contains(AccessibleState.MULTISELECTABLE)) {
2977                     s.remove(AccessibleState.MULTISELECTABLE);
2978                     firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
2979                                        AccessibleState.MULTISELECTABLE, null);
2980                 }
2981             }
2982         }
2983 
2984         /**
2985          * List Data Listener interval added method. Used to fire the visible data property change
2986          *
2987          * @param e ListDataEvent
2988          *
2989          */
2990         public void intervalAdded(ListDataEvent e) {
2991             firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
2992                                Boolean.valueOf(false), Boolean.valueOf(true));
2993         }
2994 
2995         /**
2996          * List Data Listener interval removed method. Used to fire the visible data property change
2997          *
2998          * @param e ListDataEvent
2999          *
3000          */
3001         public void intervalRemoved(ListDataEvent e) {
3002             firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
3003                                Boolean.valueOf(false), Boolean.valueOf(true));
3004         }
3005 
3006         /**
3007          * List Data Listener contents changed method. Used to fire the visible data property change
3008          *
3009          * @param e ListDataEvent
3010          *
3011          */
3012          public void contentsChanged(ListDataEvent e) {
3013              firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
3014                                 Boolean.valueOf(false), Boolean.valueOf(true));
3015          }
3016 
3017     // AccessibleContext methods
3018 
3019         /**
3020          * Get the state set of this object.
3021          *
3022          * @return an instance of AccessibleState containing the current state
3023          * of the object
3024          * @see AccessibleState
3025          */
3026         public AccessibleStateSet getAccessibleStateSet() {
3027             AccessibleStateSet states = super.getAccessibleStateSet();
3028             if (selectionModel.getSelectionMode() !=
3029                 ListSelectionModel.SINGLE_SELECTION) {
3030                 states.add(AccessibleState.MULTISELECTABLE);
3031             }
3032             return states;
3033         }
3034 
3035         /**
3036          * Get the role of this object.
3037          *
3038          * @return an instance of AccessibleRole describing the role of the
3039          * object
3040          * @see AccessibleRole
3041          */
3042         public AccessibleRole getAccessibleRole() {
3043             return AccessibleRole.LIST;
3044         }
3045 
3046         /**
3047          * Returns the <code>Accessible</code> child contained at
3048          * the local coordinate <code>Point</code>, if one exists.
3049          * Otherwise returns <code>null</code>.
3050          *
3051          * @return the <code>Accessible</code> at the specified
3052          *    location, if it exists
3053          */
3054         public Accessible getAccessibleAt(Point p) {
3055             int i = locationToIndex(p);
3056             if (i >= 0) {
3057                 return new AccessibleJListChild(JList.this, i);
3058             } else {
3059                 return null;
3060             }
3061         }
3062 
3063         /**
3064          * Returns the number of accessible children in the object.  If all
3065          * of the children of this object implement Accessible, than this
3066          * method should return the number of children of this object.
3067          *
3068          * @return the number of accessible children in the object.
3069          */
3070         public int getAccessibleChildrenCount() {
3071             return getModel().getSize();
3072         }
3073 
3074         /**
3075          * Return the nth Accessible child of the object.
3076          *
3077          * @param i zero-based index of child
3078          * @return the nth Accessible child of the object
3079          */
3080         public Accessible getAccessibleChild(int i) {
3081             if (i >= getModel().getSize()) {
3082                 return null;
3083             } else {
3084                 return new AccessibleJListChild(JList.this, i);
3085             }
3086         }
3087 
3088         /**
3089          * Get the AccessibleSelection associated with this object.  In the
3090          * implementation of the Java Accessibility API for this class,
3091          * return this object, which is responsible for implementing the
3092          * AccessibleSelection interface on behalf of itself.
3093          *
3094          * @return this object
3095          */
3096         public AccessibleSelection getAccessibleSelection() {
3097             return this;
3098         }
3099 
3100 
3101     // AccessibleSelection methods
3102 
3103         /**
3104          * Returns the number of items currently selected.
3105          * If no items are selected, the return value will be 0.
3106          *
3107          * @return the number of items currently selected.
3108          */
3109          public int getAccessibleSelectionCount() {
3110              return JList.this.getSelectedIndices().length;
3111          }
3112 
3113         /**
3114          * Returns an Accessible representing the specified selected item
3115          * in the object.  If there isn't a selection, or there are
3116          * fewer items selected than the integer passed in, the return
3117          * value will be <code>null</code>.
3118          *
3119          * @param i the zero-based index of selected items
3120          * @return an Accessible containing the selected item
3121          */
3122          public Accessible getAccessibleSelection(int i) {
3123              int len = getAccessibleSelectionCount();
3124              if (i < 0 || i >= len) {
3125                  return null;
3126              } else {
3127                  return getAccessibleChild(JList.this.getSelectedIndices()[i]);
3128              }
3129          }
3130 
3131         /**
3132          * Returns true if the current child of this object is selected.
3133          *
3134          * @param i the zero-based index of the child in this Accessible
3135          * object.
3136          * @see AccessibleContext#getAccessibleChild
3137          */
3138         public boolean isAccessibleChildSelected(int i) {
3139             return isSelectedIndex(i);
3140         }
3141 
3142         /**
3143          * Adds the specified selected item in the object to the object's
3144          * selection.  If the object supports multiple selections,
3145          * the specified item is added to any existing selection, otherwise
3146          * it replaces any existing selection in the object.  If the
3147          * specified item is already selected, this method has no effect.
3148          *
3149          * @param i the zero-based index of selectable items
3150          */
3151          public void addAccessibleSelection(int i) {
3152              JList.this.addSelectionInterval(i, i);
3153          }
3154 
3155         /**
3156          * Removes the specified selected item in the object from the object's
3157          * selection.  If the specified item isn't currently selected, this
3158          * method has no effect.
3159          *
3160          * @param i the zero-based index of selectable items
3161          */
3162          public void removeAccessibleSelection(int i) {
3163              JList.this.removeSelectionInterval(i, i);
3164          }
3165 
3166         /**
3167          * Clears the selection in the object, so that nothing in the
3168          * object is selected.
3169          */
3170          public void clearAccessibleSelection() {
3171              JList.this.clearSelection();
3172          }
3173 
3174         /**
3175          * Causes every selected item in the object to be selected
3176          * if the object supports multiple selections.
3177          */
3178          public void selectAllAccessibleSelection() {
3179              JList.this.addSelectionInterval(0, getAccessibleChildrenCount() -1);
3180          }
3181 
3182           /**
3183            * This class implements accessibility support appropriate
3184            * for list children.
3185            */
3186         protected class AccessibleJListChild extends AccessibleContext
3187                 implements Accessible, AccessibleComponent {
3188             private JList<E>     parent = null;
3189             private int       indexInParent;
3190             private Component component = null;
3191             private AccessibleContext accessibleContext = null;
3192             private ListModel<E> listModel;
3193             private ListCellRenderer<? super E> cellRenderer = null;
3194 
3195             public AccessibleJListChild(JList<E> parent, int indexInParent) {
3196                 this.parent = parent;
3197                 this.setAccessibleParent(parent);
3198                 this.indexInParent = indexInParent;
3199                 if (parent != null) {
3200                     listModel = parent.getModel();
3201                     cellRenderer = parent.getCellRenderer();
3202                 }
3203             }
3204 
3205             private Component getCurrentComponent() {
3206                 return getComponentAtIndex(indexInParent);
3207             }
3208 
3209             private AccessibleContext getCurrentAccessibleContext() {
3210                 Component c = getComponentAtIndex(indexInParent);
3211                 if (c instanceof Accessible) {
3212                     return c.getAccessibleContext();
3213                 } else {
3214                     return null;
3215                 }
3216             }
3217 
3218             private Component getComponentAtIndex(int index) {
3219                 if (index < 0 || index >= listModel.getSize()) {
3220                     return null;
3221                 }
3222                 if ((parent != null)
3223                         && (listModel != null)
3224                         && cellRenderer != null) {
3225                     E value = listModel.getElementAt(index);
3226                     boolean isSelected = parent.isSelectedIndex(index);
3227                     boolean isFocussed = parent.isFocusOwner()
3228                             && (index == parent.getLeadSelectionIndex());
3229                     return cellRenderer.getListCellRendererComponent(
3230                             parent,
3231                             value,
3232                             index,
3233                             isSelected,
3234                             isFocussed);
3235                 } else {
3236                     return null;
3237                 }
3238             }
3239 
3240 
3241             // Accessible Methods
3242            /**
3243             * Get the AccessibleContext for this object. In the
3244             * implementation of the Java Accessibility API for this class,
3245             * returns this object, which is its own AccessibleContext.
3246             *
3247             * @return this object
3248             */
3249             public AccessibleContext getAccessibleContext() {
3250                 return this;
3251             }
3252 
3253 
3254             // AccessibleContext methods
3255 
3256             public String getAccessibleName() {
3257                 AccessibleContext ac = getCurrentAccessibleContext();
3258                 if (ac != null) {
3259                     return ac.getAccessibleName();
3260                 } else {
3261                     return null;
3262                 }
3263             }
3264 
3265             public void setAccessibleName(String s) {
3266                 AccessibleContext ac = getCurrentAccessibleContext();
3267                 if (ac != null) {
3268                     ac.setAccessibleName(s);
3269                 }
3270             }
3271 
3272             public String getAccessibleDescription() {
3273                 AccessibleContext ac = getCurrentAccessibleContext();
3274                 if (ac != null) {
3275                     return ac.getAccessibleDescription();
3276                 } else {
3277                     return null;
3278                 }
3279             }
3280 
3281             public void setAccessibleDescription(String s) {
3282                 AccessibleContext ac = getCurrentAccessibleContext();
3283                 if (ac != null) {
3284                     ac.setAccessibleDescription(s);
3285                 }
3286             }
3287 
3288             public AccessibleRole getAccessibleRole() {
3289                 AccessibleContext ac = getCurrentAccessibleContext();
3290                 if (ac != null) {
3291                     return ac.getAccessibleRole();
3292                 } else {
3293                     return null;
3294                 }
3295             }
3296 
3297             public AccessibleStateSet getAccessibleStateSet() {
3298                 AccessibleContext ac = getCurrentAccessibleContext();
3299                 AccessibleStateSet s;
3300                 if (ac != null) {
3301                     s = ac.getAccessibleStateSet();
3302                 } else {
3303                     s = new AccessibleStateSet();
3304                 }
3305 
3306                 s.add(AccessibleState.SELECTABLE);
3307                 if (parent.isFocusOwner()
3308                     && (indexInParent == parent.getLeadSelectionIndex())) {
3309                     s.add(AccessibleState.ACTIVE);
3310                 }
3311                 if (parent.isSelectedIndex(indexInParent)) {
3312                     s.add(AccessibleState.SELECTED);
3313                 }
3314                 if (this.isShowing()) {
3315                     s.add(AccessibleState.SHOWING);
3316                 } else if (s.contains(AccessibleState.SHOWING)) {
3317                     s.remove(AccessibleState.SHOWING);
3318                 }
3319                 if (this.isVisible()) {
3320                     s.add(AccessibleState.VISIBLE);
3321                 } else if (s.contains(AccessibleState.VISIBLE)) {
3322                     s.remove(AccessibleState.VISIBLE);
3323                 }
3324                 s.add(AccessibleState.TRANSIENT); // cell-rendered
3325                 return s;
3326             }
3327 
3328             public int getAccessibleIndexInParent() {
3329                 return indexInParent;
3330             }
3331 
3332             public int getAccessibleChildrenCount() {
3333                 AccessibleContext ac = getCurrentAccessibleContext();
3334                 if (ac != null) {
3335                     return ac.getAccessibleChildrenCount();
3336                 } else {
3337                     return 0;
3338                 }
3339             }
3340 
3341             public Accessible getAccessibleChild(int i) {
3342                 AccessibleContext ac = getCurrentAccessibleContext();
3343                 if (ac != null) {
3344                     Accessible accessibleChild = ac.getAccessibleChild(i);
3345                     ac.setAccessibleParent(this);
3346                     return accessibleChild;
3347                 } else {
3348                     return null;
3349                 }
3350             }
3351 
3352             public Locale getLocale() {
3353                 AccessibleContext ac = getCurrentAccessibleContext();
3354                 if (ac != null) {
3355                     return ac.getLocale();
3356                 } else {
3357                     return null;
3358                 }
3359             }
3360 
3361             public void addPropertyChangeListener(PropertyChangeListener l) {
3362                 AccessibleContext ac = getCurrentAccessibleContext();
3363                 if (ac != null) {
3364                     ac.addPropertyChangeListener(l);
3365                 }
3366             }
3367 
3368             public void removePropertyChangeListener(PropertyChangeListener l) {
3369                 AccessibleContext ac = getCurrentAccessibleContext();
3370                 if (ac != null) {
3371                     ac.removePropertyChangeListener(l);
3372                 }
3373             }
3374 
3375             public AccessibleAction getAccessibleAction() {
3376                 return getCurrentAccessibleContext().getAccessibleAction();
3377             }
3378 
3379            /**
3380             * Get the AccessibleComponent associated with this object.  In the
3381             * implementation of the Java Accessibility API for this class,
3382             * return this object, which is responsible for implementing the
3383             * AccessibleComponent interface on behalf of itself.
3384             *
3385             * @return this object
3386             */
3387             public AccessibleComponent getAccessibleComponent() {
3388                 return this; // to override getBounds()
3389             }
3390 
3391             public AccessibleSelection getAccessibleSelection() {
3392                 return getCurrentAccessibleContext().getAccessibleSelection();
3393             }
3394 
3395             public AccessibleText getAccessibleText() {
3396                 return getCurrentAccessibleContext().getAccessibleText();
3397             }
3398 
3399             public AccessibleValue getAccessibleValue() {
3400                 return getCurrentAccessibleContext().getAccessibleValue();
3401             }
3402 
3403 
3404             // AccessibleComponent methods
3405 
3406             public Color getBackground() {
3407                 AccessibleContext ac = getCurrentAccessibleContext();
3408                 if (ac instanceof AccessibleComponent) {
3409                     return ((AccessibleComponent) ac).getBackground();
3410                 } else {
3411                     Component c = getCurrentComponent();
3412                     if (c != null) {
3413                         return c.getBackground();
3414                     } else {
3415                         return null;
3416                     }
3417                 }
3418             }
3419 
3420             public void setBackground(Color c) {
3421                 AccessibleContext ac = getCurrentAccessibleContext();
3422                 if (ac instanceof AccessibleComponent) {
3423                     ((AccessibleComponent) ac).setBackground(c);
3424                 } else {
3425                     Component cp = getCurrentComponent();
3426                     if (cp != null) {
3427                         cp.setBackground(c);
3428                     }
3429                 }
3430             }
3431 
3432             public Color getForeground() {
3433                 AccessibleContext ac = getCurrentAccessibleContext();
3434                 if (ac instanceof AccessibleComponent) {
3435                     return ((AccessibleComponent) ac).getForeground();
3436                 } else {
3437                     Component c = getCurrentComponent();
3438                     if (c != null) {
3439                         return c.getForeground();
3440                     } else {
3441                         return null;
3442                     }
3443                 }
3444             }
3445 
3446             public void setForeground(Color c) {
3447                 AccessibleContext ac = getCurrentAccessibleContext();
3448                 if (ac instanceof AccessibleComponent) {
3449                     ((AccessibleComponent) ac).setForeground(c);
3450                 } else {
3451                     Component cp = getCurrentComponent();
3452                     if (cp != null) {
3453                         cp.setForeground(c);
3454                     }
3455                 }
3456             }
3457 
3458             public Cursor getCursor() {
3459                 AccessibleContext ac = getCurrentAccessibleContext();
3460                 if (ac instanceof AccessibleComponent) {
3461                     return ((AccessibleComponent) ac).getCursor();
3462                 } else {
3463                     Component c = getCurrentComponent();
3464                     if (c != null) {
3465                         return c.getCursor();
3466                     } else {
3467                         Accessible ap = getAccessibleParent();
3468                         if (ap instanceof AccessibleComponent) {
3469                             return ((AccessibleComponent) ap).getCursor();
3470                         } else {
3471                             return null;
3472                         }
3473                     }
3474                 }
3475             }
3476 
3477             public void setCursor(Cursor c) {
3478                 AccessibleContext ac = getCurrentAccessibleContext();
3479                 if (ac instanceof AccessibleComponent) {
3480                     ((AccessibleComponent) ac).setCursor(c);
3481                 } else {
3482                     Component cp = getCurrentComponent();
3483                     if (cp != null) {
3484                         cp.setCursor(c);
3485                     }
3486                 }
3487             }
3488 
3489             public Font getFont() {
3490                 AccessibleContext ac = getCurrentAccessibleContext();
3491                 if (ac instanceof AccessibleComponent) {
3492                     return ((AccessibleComponent) ac).getFont();
3493                 } else {
3494                     Component c = getCurrentComponent();
3495                     if (c != null) {
3496                         return c.getFont();
3497                     } else {
3498                         return null;
3499                     }
3500                 }
3501             }
3502 
3503             public void setFont(Font f) {
3504                 AccessibleContext ac = getCurrentAccessibleContext();
3505                 if (ac instanceof AccessibleComponent) {
3506                     ((AccessibleComponent) ac).setFont(f);
3507                 } else {
3508                     Component c = getCurrentComponent();
3509                     if (c != null) {
3510                         c.setFont(f);
3511                     }
3512                 }
3513             }
3514 
3515             public FontMetrics getFontMetrics(Font f) {
3516                 AccessibleContext ac = getCurrentAccessibleContext();
3517                 if (ac instanceof AccessibleComponent) {
3518                     return ((AccessibleComponent) ac).getFontMetrics(f);
3519                 } else {
3520                     Component c = getCurrentComponent();
3521                     if (c != null) {
3522                         return c.getFontMetrics(f);
3523                     } else {
3524                         return null;
3525                     }
3526                 }
3527             }
3528 
3529             public boolean isEnabled() {
3530                 AccessibleContext ac = getCurrentAccessibleContext();
3531                 if (ac instanceof AccessibleComponent) {
3532                     return ((AccessibleComponent) ac).isEnabled();
3533                 } else {
3534                     Component c = getCurrentComponent();
3535                     if (c != null) {
3536                         return c.isEnabled();
3537                     } else {
3538                         return false;
3539                     }
3540                 }
3541             }
3542 
3543             public void setEnabled(boolean b) {
3544                 AccessibleContext ac = getCurrentAccessibleContext();
3545                 if (ac instanceof AccessibleComponent) {
3546                     ((AccessibleComponent) ac).setEnabled(b);
3547                 } else {
3548                     Component c = getCurrentComponent();
3549                     if (c != null) {
3550                         c.setEnabled(b);
3551                     }
3552                 }
3553             }
3554 
3555             public boolean isVisible() {
3556                 int fi = parent.getFirstVisibleIndex();
3557                 int li = parent.getLastVisibleIndex();
3558                 // The UI incorrectly returns a -1 for the last
3559                 // visible index if the list is smaller than the
3560                 // viewport size.
3561                 if (li == -1) {
3562                     li = parent.getModel().getSize() - 1;
3563                 }
3564                 return ((indexInParent >= fi)
3565                         && (indexInParent <= li));
3566             }
3567 
3568             public void setVisible(boolean b) {
3569             }
3570 
3571             public boolean isShowing() {
3572                 return (parent.isShowing() && isVisible());
3573             }
3574 
3575             public boolean contains(Point p) {
3576                 AccessibleContext ac = getCurrentAccessibleContext();
3577                 if (ac instanceof AccessibleComponent) {
3578                     Rectangle r = ((AccessibleComponent) ac).getBounds();
3579                     return r.contains(p);
3580                 } else {
3581                     Component c = getCurrentComponent();
3582                     if (c != null) {
3583                         Rectangle r = c.getBounds();
3584                         return r.contains(p);
3585                     } else {
3586                         return getBounds().contains(p);
3587                     }
3588                 }
3589             }
3590 
3591             public Point getLocationOnScreen() {
3592                 if (parent != null) {
3593                     Point listLocation = parent.getLocationOnScreen();
3594                     Point componentLocation = parent.indexToLocation(indexInParent);
3595                     if (componentLocation != null) {
3596                         componentLocation.translate(listLocation.x, listLocation.y);
3597                         return componentLocation;
3598                     } else {
3599                         return null;
3600                     }
3601                 } else {
3602                     return null;
3603                 }
3604             }
3605 
3606             public Point getLocation() {
3607                 if (parent != null) {
3608                     return parent.indexToLocation(indexInParent);
3609                 } else {
3610                     return null;
3611                 }
3612             }
3613 
3614             public void setLocation(Point p) {
3615                 if ((parent != null)  && (parent.contains(p))) {
3616                     ensureIndexIsVisible(indexInParent);
3617                 }
3618             }
3619 
3620             public Rectangle getBounds() {
3621                 if (parent != null) {
3622                     return parent.getCellBounds(indexInParent,indexInParent);
3623                 } else {
3624                     return null;
3625                 }
3626             }
3627 
3628             public void setBounds(Rectangle r) {
3629                 AccessibleContext ac = getCurrentAccessibleContext();
3630                 if (ac instanceof AccessibleComponent) {
3631                     ((AccessibleComponent) ac).setBounds(r);
3632                 }
3633             }
3634 
3635             public Dimension getSize() {
3636                 Rectangle cellBounds = this.getBounds();
3637                 if (cellBounds != null) {
3638                     return cellBounds.getSize();
3639                 } else {
3640                     return null;
3641                 }
3642             }
3643 
3644             public void setSize (Dimension d) {
3645                 AccessibleContext ac = getCurrentAccessibleContext();
3646                 if (ac instanceof AccessibleComponent) {
3647                     ((AccessibleComponent) ac).setSize(d);
3648                 } else {
3649                     Component c = getCurrentComponent();
3650                     if (c != null) {
3651                         c.setSize(d);
3652                     }
3653                 }
3654             }
3655 
3656             public Accessible getAccessibleAt(Point p) {
3657                 AccessibleContext ac = getCurrentAccessibleContext();
3658                 if (ac instanceof AccessibleComponent) {
3659                     return ((AccessibleComponent) ac).getAccessibleAt(p);
3660                 } else {
3661                     return null;
3662                 }
3663             }
3664 
3665             public boolean isFocusTraversable() {
3666                 AccessibleContext ac = getCurrentAccessibleContext();
3667                 if (ac instanceof AccessibleComponent) {
3668                     return ((AccessibleComponent) ac).isFocusTraversable();
3669                 } else {
3670                     Component c = getCurrentComponent();
3671                     if (c != null) {
3672                         return c.isFocusTraversable();
3673                     } else {
3674                         return false;
3675                     }
3676                 }
3677             }
3678 
3679             public void requestFocus() {
3680                 AccessibleContext ac = getCurrentAccessibleContext();
3681                 if (ac instanceof AccessibleComponent) {
3682                     ((AccessibleComponent) ac).requestFocus();
3683                 } else {
3684                     Component c = getCurrentComponent();
3685                     if (c != null) {
3686                         c.requestFocus();
3687                     }
3688                 }
3689             }
3690 
3691             public void addFocusListener(FocusListener l) {
3692                 AccessibleContext ac = getCurrentAccessibleContext();
3693                 if (ac instanceof AccessibleComponent) {
3694                     ((AccessibleComponent) ac).addFocusListener(l);
3695                 } else {
3696                     Component c = getCurrentComponent();
3697                     if (c != null) {
3698                         c.addFocusListener(l);
3699                     }
3700                 }
3701             }
3702 
3703             public void removeFocusListener(FocusListener l) {
3704                 AccessibleContext ac = getCurrentAccessibleContext();
3705                 if (ac instanceof AccessibleComponent) {
3706                     ((AccessibleComponent) ac).removeFocusListener(l);
3707                 } else {
3708                     Component c = getCurrentComponent();
3709                     if (c != null) {
3710                         c.removeFocusListener(l);
3711                     }
3712                 }
3713             }
3714 
3715             // TIGER - 4733624
3716             /**
3717              * Returns the icon for the element renderer, as the only item
3718              * of an array of <code>AccessibleIcon</code>s or a <code>null</code> array
3719              * if the renderer component contains no icons.
3720              *
3721              * @return an array containing the accessible icon
3722              *         or a <code>null</code> array if none
3723              * @since 1.3
3724              */
3725             public AccessibleIcon [] getAccessibleIcon() {
3726                 AccessibleContext ac = getCurrentAccessibleContext();
3727                 if (ac != null) {
3728                     return ac.getAccessibleIcon();
3729                 } else {
3730                     return null;
3731                 }
3732             }
3733         } // inner class AccessibleJListChild
3734     } // inner class AccessibleJList
3735 }