rev 14331 : 8074286: Add getSelectedIndices() to ListSelectionModel
Reviewed-by: serb, psadhukhan

   1 /*
   2  * Copyright (c) 1997, 2020, 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.awt.AWTAccessor;
  52 import sun.awt.AWTAccessor.MouseEventAccessor;
  53 import sun.swing.SwingUtilities2;
  54 import sun.swing.SwingUtilities2.Section;
  55 import static sun.swing.SwingUtilities2.Section.*;
  56 
  57 
  58 /**
  59  * A component that displays a list of objects and allows the user to select
  60  * one or more items. A separate model, {@code ListModel}, maintains the
  61  * contents of the list.
  62  * <p>
  63  * It's easy to display an array or Vector of objects, using the {@code JList}
  64  * constructor that automatically builds a read-only {@code ListModel} instance
  65  * for you:
  66  * <pre>
  67  * {@code
  68  * // Create a JList that displays strings from an array
  69  *
  70  * String[] data = {"one", "two", "three", "four"};
  71  * JList<String> myList = new JList<String>(data);
  72  *
  73  * // Create a JList that displays the superclasses of JList.class, by
  74  * // creating it with a Vector populated with this data
  75  *
  76  * Vector<Class<?>> superClasses = new Vector<Class<?>>();
  77  * Class<JList> rootClass = javax.swing.JList.class;
  78  * for(Class<?> cls = rootClass; cls != null; cls = cls.getSuperclass()) {
  79  *     superClasses.addElement(cls);
  80  * }
  81  * JList<Class<?>> myList = new JList<Class<?>>(superClasses);
  82  *
  83  * // The automatically created model is stored in JList's "model"
  84  * // property, which you can retrieve
  85  *
  86  * ListModel<Class<?>> model = myList.getModel();
  87  * for(int i = 0; i < model.getSize(); i++) {
  88  *     System.out.println(model.getElementAt(i));
  89  * }
  90  * }
  91  * </pre>
  92  * <p>
  93  * A {@code ListModel} can be supplied directly to a {@code JList} by way of a
  94  * constructor or the {@code setModel} method. The contents need not be static -
  95  * the number of items, and the values of items can change over time. A correct
  96  * {@code ListModel} implementation notifies the set of
  97  * {@code javax.swing.event.ListDataListener}s that have been added to it, each
  98  * time a change occurs. These changes are characterized by a
  99  * {@code javax.swing.event.ListDataEvent}, which identifies the range of list
 100  * indices that have been modified, added, or removed. {@code JList}'s
 101  * {@code ListUI} is responsible for keeping the visual representation up to
 102  * date with changes, by listening to the model.
 103  * <p>
 104  * Simple, dynamic-content, {@code JList} applications can use the
 105  * {@code DefaultListModel} class to maintain list elements. This class
 106  * implements the {@code ListModel} interface and also provides a
 107  * <code>java.util.Vector</code>-like API. Applications that need a more
 108  * custom <code>ListModel</code> implementation may instead wish to subclass
 109  * {@code AbstractListModel}, which provides basic support for managing and
 110  * notifying listeners. For example, a read-only implementation of
 111  * {@code AbstractListModel}:
 112  * <pre>
 113  * {@code
 114  * // This list model has about 2^16 elements.  Enjoy scrolling.
 115  *
 116  * ListModel<String> bigData = new AbstractListModel<String>() {
 117  *     public int getSize() { return Short.MAX_VALUE; }
 118  *     public String getElementAt(int index) { return "Index " + index; }
 119  * };
 120  * }
 121  * </pre>
 122  * <p>
 123  * The selection state of a {@code JList} is managed by another separate
 124  * model, an instance of {@code ListSelectionModel}. {@code JList} is
 125  * initialized with a selection model on construction, and also contains
 126  * methods to query or set this selection model. Additionally, {@code JList}
 127  * provides convenient methods for easily managing the selection. These methods,
 128  * such as {@code setSelectedIndex} and {@code getSelectedValue}, are cover
 129  * methods that take care of the details of interacting with the selection
 130  * model. By default, {@code JList}'s selection model is configured to allow any
 131  * combination of items to be selected at a time; selection mode
 132  * {@code MULTIPLE_INTERVAL_SELECTION}. The selection mode can be changed
 133  * on the selection model directly, or via {@code JList}'s cover method.
 134  * Responsibility for updating the selection model in response to user gestures
 135  * lies with the list's {@code ListUI}.
 136  * <p>
 137  * A correct {@code ListSelectionModel} implementation notifies the set of
 138  * {@code javax.swing.event.ListSelectionListener}s that have been added to it
 139  * each time a change to the selection occurs. These changes are characterized
 140  * by a {@code javax.swing.event.ListSelectionEvent}, which identifies the range
 141  * of the selection change.
 142  * <p>
 143  * The preferred way to listen for changes in list selection is to add
 144  * {@code ListSelectionListener}s directly to the {@code JList}. {@code JList}
 145  * then takes care of listening to the the selection model and notifying your
 146  * listeners of change.
 147  * <p>
 148  * Responsibility for listening to selection changes in order to keep the list's
 149  * visual representation up to date lies with the list's {@code ListUI}.
 150  * <p>
 151  * <a name="renderer"></a>
 152  * Painting of cells in a {@code JList} is handled by a delegate called a
 153  * cell renderer, installed on the list as the {@code cellRenderer} property.
 154  * The renderer provides a {@code java.awt.Component} that is used
 155  * like a "rubber stamp" to paint the cells. Each time a cell needs to be
 156  * painted, the list's {@code ListUI} asks the cell renderer for the component,
 157  * moves it into place, and has it paint the contents of the cell by way of its
 158  * {@code paint} method. A default cell renderer, which uses a {@code JLabel}
 159  * component to render, is installed by the lists's {@code ListUI}. You can
 160  * substitute your own renderer using code like this:
 161  * <pre>
 162  * {@code
 163  *  // Display an icon and a string for each object in the list.
 164  *
 165  * class MyCellRenderer extends JLabel implements ListCellRenderer<Object> {
 166  *     final static ImageIcon longIcon = new ImageIcon("long.gif");
 167  *     final static ImageIcon shortIcon = new ImageIcon("short.gif");
 168  *
 169  *     // This is the only method defined by ListCellRenderer.
 170  *     // We just reconfigure the JLabel each time we're called.
 171  *
 172  *     public Component getListCellRendererComponent(
 173  *       JList<?> list,           // the list
 174  *       Object value,            // value to display
 175  *       int index,               // cell index
 176  *       boolean isSelected,      // is the cell selected
 177  *       boolean cellHasFocus)    // does the cell have focus
 178  *     {
 179  *         String s = value.toString();
 180  *         setText(s);
 181  *         setIcon((s.length() > 10) ? longIcon : shortIcon);
 182  *         if (isSelected) {
 183  *             setBackground(list.getSelectionBackground());
 184  *             setForeground(list.getSelectionForeground());
 185  *         } else {
 186  *             setBackground(list.getBackground());
 187  *             setForeground(list.getForeground());
 188  *         }
 189  *         setEnabled(list.isEnabled());
 190  *         setFont(list.getFont());
 191  *         setOpaque(true);
 192  *         return this;
 193  *     }
 194  * }
 195  *
 196  * myList.setCellRenderer(new MyCellRenderer());
 197  * }
 198  * </pre>
 199  * <p>
 200  * Another job for the cell renderer is in helping to determine sizing
 201  * information for the list. By default, the list's {@code ListUI} determines
 202  * the size of cells by asking the cell renderer for its preferred
 203  * size for each list item. This can be expensive for large lists of items.
 204  * To avoid these calculations, you can set a {@code fixedCellWidth} and
 205  * {@code fixedCellHeight} on the list, or have these values calculated
 206  * automatically based on a single prototype value:
 207  * <a name="prototype_example"></a>
 208  * <pre>
 209  * {@code
 210  * JList<String> bigDataList = new JList<String>(bigData);
 211  *
 212  * // We don't want the JList implementation to compute the width
 213  * // or height of all of the list cells, so we give it a string
 214  * // that's as big as we'll need for any cell.  It uses this to
 215  * // compute values for the fixedCellWidth and fixedCellHeight
 216  * // properties.
 217  *
 218  * bigDataList.setPrototypeCellValue("Index 1234567890");
 219  * }
 220  * </pre>
 221  * <p>
 222  * {@code JList} doesn't implement scrolling directly. To create a list that
 223  * scrolls, make it the viewport view of a {@code JScrollPane}. For example:
 224  * <pre>
 225  * JScrollPane scrollPane = new JScrollPane(myList);
 226  *
 227  * // Or in two steps:
 228  * JScrollPane scrollPane = new JScrollPane();
 229  * scrollPane.getViewport().setView(myList);
 230  * </pre>
 231  * <p>
 232  * {@code JList} doesn't provide any special handling of double or triple
 233  * (or N) mouse clicks, but it's easy to add a {@code MouseListener} if you
 234  * wish to take action on these events. Use the {@code locationToIndex}
 235  * method to determine what cell was clicked. For example:
 236  * <pre>
 237  * MouseListener mouseListener = new MouseAdapter() {
 238  *     public void mouseClicked(MouseEvent e) {
 239  *         if (e.getClickCount() == 2) {
 240  *             int index = list.locationToIndex(e.getPoint());
 241  *             System.out.println("Double clicked on Item " + index);
 242  *          }
 243  *     }
 244  * };
 245  * list.addMouseListener(mouseListener);
 246  * </pre>
 247  * <p>
 248  * <strong>Warning:</strong> Swing is not thread safe. For more
 249  * information see <a
 250  * href="package-summary.html#threading">Swing's Threading
 251  * Policy</a>.
 252  * <p>
 253  * <strong>Warning:</strong>
 254  * Serialized objects of this class will not be compatible with
 255  * future Swing releases. The current serialization support is
 256  * appropriate for short term storage or RMI between applications running
 257  * the same version of Swing.  As of 1.4, support for long term storage
 258  * of all JavaBeans&trade;
 259  * has been added to the <code>java.beans</code> package.
 260  * Please see {@link java.beans.XMLEncoder}.
 261  * <p>
 262  * See <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/list.html">How to Use Lists</a>
 263  * in <a href="https://docs.oracle.com/javase/tutorial/"><em>The Java Tutorial</em></a>
 264  * for further documentation.
 265  * <p>
 266  * @see ListModel
 267  * @see AbstractListModel
 268  * @see DefaultListModel
 269  * @see ListSelectionModel
 270  * @see DefaultListSelectionModel
 271  * @see ListCellRenderer
 272  * @see DefaultListCellRenderer
 273  *
 274  * @param <E> the type of the elements of this list
 275  *
 276  * @beaninfo
 277  *   attribute: isContainer false
 278  * description: A component which allows for the selection of one or more objects from a list.
 279  *
 280  * @author Hans Muller
 281  */
 282 public class JList<E> extends JComponent implements Scrollable, Accessible
 283 {
 284     /**
 285      * @see #getUIClassID
 286      * @see #readObject
 287      */
 288     private static final String uiClassID = "ListUI";
 289 
 290     /**
 291      * Indicates a vertical layout of cells, in a single column;
 292      * the default layout.
 293      * @see #setLayoutOrientation
 294      * @since 1.4
 295      */
 296     public static final int VERTICAL = 0;
 297 
 298     /**
 299      * Indicates a "newspaper style" layout with cells flowing vertically
 300      * then horizontally.
 301      * @see #setLayoutOrientation
 302      * @since 1.4
 303      */
 304     public static final int VERTICAL_WRAP = 1;
 305 
 306     /**
 307      * Indicates a "newspaper style" layout with cells flowing horizontally
 308      * then vertically.
 309      * @see #setLayoutOrientation
 310      * @since 1.4
 311      */
 312     public static final int HORIZONTAL_WRAP = 2;
 313 
 314     private int fixedCellWidth = -1;
 315     private int fixedCellHeight = -1;
 316     private int horizontalScrollIncrement = -1;
 317     private E prototypeCellValue;
 318     private int visibleRowCount = 8;
 319     private Color selectionForeground;
 320     private Color selectionBackground;
 321     private boolean dragEnabled;
 322 
 323     private ListSelectionModel selectionModel;
 324     private ListModel<E> dataModel;
 325     private ListCellRenderer<? super E> cellRenderer;
 326     private ListSelectionListener selectionListener;
 327 
 328     /**
 329      * How to lay out the cells; defaults to <code>VERTICAL</code>.
 330      */
 331     private int layoutOrientation;
 332 
 333     /**
 334      * The drop mode for this component.
 335      */
 336     private DropMode dropMode = DropMode.USE_SELECTION;
 337 
 338     /**
 339      * The drop location.
 340      */
 341     private transient DropLocation dropLocation;
 342 
 343     /**
 344      * A subclass of <code>TransferHandler.DropLocation</code> representing
 345      * a drop location for a <code>JList</code>.
 346      *
 347      * @see #getDropLocation
 348      * @since 1.6
 349      */
 350     public static final class DropLocation extends TransferHandler.DropLocation {
 351         private final int index;
 352         private final boolean isInsert;
 353 
 354         private DropLocation(Point p, int index, boolean isInsert) {
 355             super(p);
 356             this.index = index;
 357             this.isInsert = isInsert;
 358         }
 359 
 360         /**
 361          * Returns the index where dropped data should be placed in the
 362          * list. Interpretation of the value depends on the drop mode set on
 363          * the associated component. If the drop mode is either
 364          * <code>DropMode.USE_SELECTION</code> or <code>DropMode.ON</code>,
 365          * the return value is an index of a row in the list. If the drop mode is
 366          * <code>DropMode.INSERT</code>, the return value refers to the index
 367          * where the data should be inserted. If the drop mode is
 368          * <code>DropMode.ON_OR_INSERT</code>, the value of
 369          * <code>isInsert()</code> indicates whether the index is an index
 370          * of a row, or an insert index.
 371          * <p>
 372          * <code>-1</code> indicates that the drop occurred over empty space,
 373          * and no index could be calculated.
 374          *
 375          * @return the drop index
 376          */
 377         public int getIndex() {
 378             return index;
 379         }
 380 
 381         /**
 382          * Returns whether or not this location represents an insert
 383          * location.
 384          *
 385          * @return whether or not this is an insert location
 386          */
 387         public boolean isInsert() {
 388             return isInsert;
 389         }
 390 
 391         /**
 392          * Returns a string representation of this drop location.
 393          * This method is intended to be used for debugging purposes,
 394          * and the content and format of the returned string may vary
 395          * between implementations.
 396          *
 397          * @return a string representation of this drop location
 398          */
 399         public String toString() {
 400             return getClass().getName()
 401                    + "[dropPoint=" + getDropPoint() + ","
 402                    + "index=" + index + ","
 403                    + "insert=" + isInsert + "]";
 404         }
 405     }
 406 
 407     /**
 408      * Constructs a {@code JList} that displays elements from the specified,
 409      * {@code non-null}, model. All {@code JList} constructors delegate to
 410      * this one.
 411      * <p>
 412      * This constructor registers the list with the {@code ToolTipManager},
 413      * allowing for tooltips to be provided by the cell renderers.
 414      *
 415      * @param dataModel the model for the list
 416      * @exception IllegalArgumentException if the model is {@code null}
 417      */
 418     public JList(ListModel<E> dataModel)
 419     {
 420         if (dataModel == null) {
 421             throw new IllegalArgumentException("dataModel must be non null");
 422         }
 423 
 424         // Register with the ToolTipManager so that tooltips from the
 425         // renderer show through.
 426         ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
 427         toolTipManager.registerComponent(this);
 428 
 429         layoutOrientation = VERTICAL;
 430 
 431         this.dataModel = dataModel;
 432         selectionModel = createSelectionModel();
 433         setAutoscrolls(true);
 434         setOpaque(true);
 435         updateUI();
 436     }
 437 
 438 
 439     /**
 440      * Constructs a <code>JList</code> that displays the elements in
 441      * the specified array. This constructor creates a read-only model
 442      * for the given array, and then delegates to the constructor that
 443      * takes a {@code ListModel}.
 444      * <p>
 445      * Attempts to pass a {@code null} value to this method results in
 446      * undefined behavior and, most likely, exceptions. The created model
 447      * references the given array directly. Attempts to modify the array
 448      * after constructing the list results in undefined behavior.
 449      *
 450      * @param  listData  the array of Objects to be loaded into the data model,
 451      *                   {@code non-null}
 452      */
 453     public JList(final E[] listData)
 454     {
 455         this (
 456             new AbstractListModel<E>() {
 457                 public int getSize() { return listData.length; }
 458                 public E getElementAt(int i) { return listData[i]; }
 459             }
 460         );
 461     }
 462 
 463 
 464     /**
 465      * Constructs a <code>JList</code> that displays the elements in
 466      * the specified <code>Vector</code>. This constructor creates a read-only
 467      * model for the given {@code Vector}, and then delegates to the constructor
 468      * that takes a {@code ListModel}.
 469      * <p>
 470      * Attempts to pass a {@code null} value to this method results in
 471      * undefined behavior and, most likely, exceptions. The created model
 472      * references the given {@code Vector} directly. Attempts to modify the
 473      * {@code Vector} after constructing the list results in undefined behavior.
 474      *
 475      * @param  listData  the <code>Vector</code> to be loaded into the
 476      *                   data model, {@code non-null}
 477      */
 478     public JList(final Vector<? extends E> listData) {
 479         this (
 480             new AbstractListModel<E>() {
 481                 public int getSize() { return listData.size(); }
 482                 public E getElementAt(int i) { return listData.elementAt(i); }
 483             }
 484         );
 485     }
 486 
 487 
 488     /**
 489      * Constructs a <code>JList</code> with an empty, read-only, model.
 490      */
 491     public JList() {
 492         this (
 493             new AbstractListModel<E>() {
 494               public int getSize() { return 0; }
 495               public E getElementAt(int i) { throw new IndexOutOfBoundsException("No Data Model"); }
 496             }
 497         );
 498     }
 499 
 500 
 501     /**
 502      * Returns the {@code ListUI}, the look and feel object that
 503      * renders this component.
 504      *
 505      * @return the <code>ListUI</code> object that renders this component
 506      */
 507     public ListUI getUI() {
 508         return (ListUI)ui;
 509     }
 510 
 511 
 512     /**
 513      * Sets the {@code ListUI}, the look and feel object that
 514      * renders this component.
 515      *
 516      * @param ui  the <code>ListUI</code> object
 517      * @see UIDefaults#getUI
 518      * @beaninfo
 519      *        bound: true
 520      *       hidden: true
 521      *    attribute: visualUpdate true
 522      *  description: The UI object that implements the Component's LookAndFeel.
 523      */
 524     public void setUI(ListUI ui) {
 525         super.setUI(ui);
 526     }
 527 
 528 
 529     /**
 530      * Resets the {@code ListUI} property by setting it to the value provided
 531      * by the current look and feel. If the current cell renderer was installed
 532      * by the developer (rather than the look and feel itself), this also causes
 533      * the cell renderer and its children to be updated, by calling
 534      * {@code SwingUtilities.updateComponentTreeUI} on it.
 535      *
 536      * @see UIManager#getUI
 537      * @see SwingUtilities#updateComponentTreeUI
 538      */
 539     public void updateUI() {
 540         setUI((ListUI)UIManager.getUI(this));
 541 
 542         ListCellRenderer<? super E> renderer = getCellRenderer();
 543         if (renderer instanceof Component) {
 544             SwingUtilities.updateComponentTreeUI((Component)renderer);
 545         }
 546     }
 547 
 548 
 549     /**
 550      * Returns {@code "ListUI"}, the <code>UIDefaults</code> key used to look
 551      * up the name of the {@code javax.swing.plaf.ListUI} class that defines
 552      * the look and feel for this component.
 553      *
 554      * @return the string "ListUI"
 555      * @see JComponent#getUIClassID
 556      * @see UIDefaults#getUI
 557      */
 558     public String getUIClassID() {
 559         return uiClassID;
 560     }
 561 
 562 
 563     /* -----private-----
 564      * This method is called by setPrototypeCellValue and setCellRenderer
 565      * to update the fixedCellWidth and fixedCellHeight properties from the
 566      * current value of prototypeCellValue (if it's non null).
 567      * <p>
 568      * This method sets fixedCellWidth and fixedCellHeight but does <b>not</b>
 569      * generate PropertyChangeEvents for them.
 570      *
 571      * @see #setPrototypeCellValue
 572      * @see #setCellRenderer
 573      */
 574     private void updateFixedCellSize()
 575     {
 576         ListCellRenderer<? super E> cr = getCellRenderer();
 577         E value = getPrototypeCellValue();
 578 
 579         if ((cr != null) && (value != null)) {
 580             Component c = cr.getListCellRendererComponent(this, value, 0, false, false);
 581 
 582             /* The ListUI implementation will add Component c to its private
 583              * CellRendererPane however we can't assume that's already
 584              * been done here.  So we temporarily set the one "inherited"
 585              * property that may affect the renderer components preferred size:
 586              * its font.
 587              */
 588             Font f = c.getFont();
 589             c.setFont(getFont());
 590 
 591             Dimension d = c.getPreferredSize();
 592             fixedCellWidth = d.width;
 593             fixedCellHeight = d.height;
 594 
 595             c.setFont(f);
 596         }
 597     }
 598 
 599 
 600     /**
 601      * Returns the "prototypical" cell value -- a value used to calculate a
 602      * fixed width and height for cells. This can be {@code null} if there
 603      * is no such value.
 604      *
 605      * @return the value of the {@code prototypeCellValue} property
 606      * @see #setPrototypeCellValue
 607      */
 608     public E getPrototypeCellValue() {
 609         return prototypeCellValue;
 610     }
 611 
 612     /**
 613      * Sets the {@code prototypeCellValue} property, and then (if the new value
 614      * is {@code non-null}), computes the {@code fixedCellWidth} and
 615      * {@code fixedCellHeight} properties by requesting the cell renderer
 616      * component for the given value (and index 0) from the cell renderer, and
 617      * using that component's preferred size.
 618      * <p>
 619      * This method is useful when the list is too long to allow the
 620      * {@code ListUI} to compute the width/height of each cell, and there is a
 621      * single cell value that is known to occupy as much space as any of the
 622      * others, a so-called prototype.
 623      * <p>
 624      * While all three of the {@code prototypeCellValue},
 625      * {@code fixedCellHeight}, and {@code fixedCellWidth} properties may be
 626      * modified by this method, {@code PropertyChangeEvent} notifications are
 627      * only sent when the {@code prototypeCellValue} property changes.
 628      * <p>
 629      * To see an example which sets this property, see the
 630      * <a href="#prototype_example">class description</a> above.
 631      * <p>
 632      * The default value of this property is <code>null</code>.
 633      * <p>
 634      * This is a JavaBeans bound property.
 635      *
 636      * @param prototypeCellValue  the value on which to base
 637      *                          <code>fixedCellWidth</code> and
 638      *                          <code>fixedCellHeight</code>
 639      * @see #getPrototypeCellValue
 640      * @see #setFixedCellWidth
 641      * @see #setFixedCellHeight
 642      * @see JComponent#addPropertyChangeListener
 643      * @beaninfo
 644      *       bound: true
 645      *   attribute: visualUpdate true
 646      * description: The cell prototype value, used to compute cell width and height.
 647      */
 648     public void setPrototypeCellValue(E prototypeCellValue) {
 649         E oldValue = this.prototypeCellValue;
 650         this.prototypeCellValue = prototypeCellValue;
 651 
 652         /* If the prototypeCellValue has changed and is non-null,
 653          * then recompute fixedCellWidth and fixedCellHeight.
 654          */
 655 
 656         if ((prototypeCellValue != null) && !prototypeCellValue.equals(oldValue)) {
 657             updateFixedCellSize();
 658         }
 659 
 660         firePropertyChange("prototypeCellValue", oldValue, prototypeCellValue);
 661     }
 662 
 663 
 664     /**
 665      * Returns the value of the {@code fixedCellWidth} property.
 666      *
 667      * @return the fixed cell width
 668      * @see #setFixedCellWidth
 669      */
 670     public int getFixedCellWidth() {
 671         return fixedCellWidth;
 672     }
 673 
 674     /**
 675      * Sets a fixed value to be used for the width of every cell in the list.
 676      * If {@code width} is -1, cell widths are computed in the {@code ListUI}
 677      * by applying <code>getPreferredSize</code> to the cell renderer component
 678      * for each list element.
 679      * <p>
 680      * The default value of this property is {@code -1}.
 681      * <p>
 682      * This is a JavaBeans bound property.
 683      *
 684      * @param width the width to be used for all cells in the list
 685      * @see #setPrototypeCellValue
 686      * @see #setFixedCellWidth
 687      * @see JComponent#addPropertyChangeListener
 688      * @beaninfo
 689      *       bound: true
 690      *   attribute: visualUpdate true
 691      * description: Defines a fixed cell width when greater than zero.
 692      */
 693     public void setFixedCellWidth(int width) {
 694         int oldValue = fixedCellWidth;
 695         fixedCellWidth = width;
 696         firePropertyChange("fixedCellWidth", oldValue, fixedCellWidth);
 697     }
 698 
 699 
 700     /**
 701      * Returns the value of the {@code fixedCellHeight} property.
 702      *
 703      * @return the fixed cell height
 704      * @see #setFixedCellHeight
 705      */
 706     public int getFixedCellHeight() {
 707         return fixedCellHeight;
 708     }
 709 
 710     /**
 711      * Sets a fixed value to be used for the height of every cell in the list.
 712      * If {@code height} is -1, cell heights are computed in the {@code ListUI}
 713      * by applying <code>getPreferredSize</code> to the cell renderer component
 714      * for each list element.
 715      * <p>
 716      * The default value of this property is {@code -1}.
 717      * <p>
 718      * This is a JavaBeans bound property.
 719      *
 720      * @param height the height to be used for for all cells in the list
 721      * @see #setPrototypeCellValue
 722      * @see #setFixedCellWidth
 723      * @see JComponent#addPropertyChangeListener
 724      * @beaninfo
 725      *       bound: true
 726      *   attribute: visualUpdate true
 727      * description: Defines a fixed cell height when greater than zero.
 728      */
 729     public void setFixedCellHeight(int height) {
 730         int oldValue = fixedCellHeight;
 731         fixedCellHeight = height;
 732         firePropertyChange("fixedCellHeight", oldValue, fixedCellHeight);
 733     }
 734 
 735 
 736     /**
 737      * Returns the object responsible for painting list items.
 738      *
 739      * @return the value of the {@code cellRenderer} property
 740      * @see #setCellRenderer
 741      */
 742     @Transient
 743     public ListCellRenderer<? super E> getCellRenderer() {
 744         return cellRenderer;
 745     }
 746 
 747     /**
 748      * Sets the delegate that is used to paint each cell in the list.
 749      * The job of a cell renderer is discussed in detail in the
 750      * <a href="#renderer">class level documentation</a>.
 751      * <p>
 752      * If the {@code prototypeCellValue} property is {@code non-null},
 753      * setting the cell renderer also causes the {@code fixedCellWidth} and
 754      * {@code fixedCellHeight} properties to be re-calculated. Only one
 755      * <code>PropertyChangeEvent</code> is generated however -
 756      * for the <code>cellRenderer</code> property.
 757      * <p>
 758      * The default value of this property is provided by the {@code ListUI}
 759      * delegate, i.e. by the look and feel implementation.
 760      * <p>
 761      * This is a JavaBeans bound property.
 762      *
 763      * @param cellRenderer the <code>ListCellRenderer</code>
 764      *                          that paints list cells
 765      * @see #getCellRenderer
 766      * @beaninfo
 767      *       bound: true
 768      *   attribute: visualUpdate true
 769      * description: The component used to draw the cells.
 770      */
 771     public void setCellRenderer(ListCellRenderer<? super E> cellRenderer) {
 772         ListCellRenderer<? super E> oldValue = this.cellRenderer;
 773         this.cellRenderer = cellRenderer;
 774 
 775         /* If the cellRenderer has changed and prototypeCellValue
 776          * was set, then recompute fixedCellWidth and fixedCellHeight.
 777          */
 778         if ((cellRenderer != null) && !cellRenderer.equals(oldValue)) {
 779             updateFixedCellSize();
 780         }
 781 
 782         firePropertyChange("cellRenderer", oldValue, cellRenderer);
 783     }
 784 
 785 
 786     /**
 787      * Returns the color used to draw the foreground of selected items.
 788      * {@code DefaultListCellRenderer} uses this color to draw the foreground
 789      * of items in the selected state, as do the renderers installed by most
 790      * {@code ListUI} implementations.
 791      *
 792      * @return the color to draw the foreground of selected items
 793      * @see #setSelectionForeground
 794      * @see DefaultListCellRenderer
 795      */
 796     public Color getSelectionForeground() {
 797         return selectionForeground;
 798     }
 799 
 800 
 801     /**
 802      * Sets the color used to draw the foreground of selected items, which
 803      * cell renderers can use to render text and graphics.
 804      * {@code DefaultListCellRenderer} uses this color to draw the foreground
 805      * of items in the selected state, as do the renderers installed by most
 806      * {@code ListUI} implementations.
 807      * <p>
 808      * The default value of this property is defined by the look and feel
 809      * implementation.
 810      * <p>
 811      * This is a JavaBeans bound property.
 812      *
 813      * @param selectionForeground  the {@code Color} to use in the foreground
 814      *                             for selected list items
 815      * @see #getSelectionForeground
 816      * @see #setSelectionBackground
 817      * @see #setForeground
 818      * @see #setBackground
 819      * @see #setFont
 820      * @see DefaultListCellRenderer
 821      * @beaninfo
 822      *       bound: true
 823      *   attribute: visualUpdate true
 824      * description: The foreground color of selected cells.
 825      */
 826     public void setSelectionForeground(Color selectionForeground) {
 827         Color oldValue = this.selectionForeground;
 828         this.selectionForeground = selectionForeground;
 829         firePropertyChange("selectionForeground", oldValue, selectionForeground);
 830     }
 831 
 832 
 833     /**
 834      * Returns the color used to draw the background of selected items.
 835      * {@code DefaultListCellRenderer} uses this color to draw the background
 836      * of items in the selected state, as do the renderers installed by most
 837      * {@code ListUI} implementations.
 838      *
 839      * @return the color to draw the background of selected items
 840      * @see #setSelectionBackground
 841      * @see DefaultListCellRenderer
 842      */
 843     public Color getSelectionBackground() {
 844         return selectionBackground;
 845     }
 846 
 847 
 848     /**
 849      * Sets the color used to draw the background of selected items, which
 850      * cell renderers can use fill selected cells.
 851      * {@code DefaultListCellRenderer} uses this color to fill the background
 852      * of items in the selected state, as do the renderers installed by most
 853      * {@code ListUI} implementations.
 854      * <p>
 855      * The default value of this property is defined by the look
 856      * and feel implementation.
 857      * <p>
 858      * This is a JavaBeans bound property.
 859      *
 860      * @param selectionBackground  the {@code Color} to use for the
 861      *                             background of selected cells
 862      * @see #getSelectionBackground
 863      * @see #setSelectionForeground
 864      * @see #setForeground
 865      * @see #setBackground
 866      * @see #setFont
 867      * @see DefaultListCellRenderer
 868      * @beaninfo
 869      *       bound: true
 870      *   attribute: visualUpdate true
 871      * description: The background color of selected cells.
 872      */
 873     public void setSelectionBackground(Color selectionBackground) {
 874         Color oldValue = this.selectionBackground;
 875         this.selectionBackground = selectionBackground;
 876         firePropertyChange("selectionBackground", oldValue, selectionBackground);
 877     }
 878 
 879 
 880     /**
 881      * Returns the value of the {@code visibleRowCount} property. See the
 882      * documentation for {@link #setVisibleRowCount} for details on how to
 883      * interpret this value.
 884      *
 885      * @return the value of the {@code visibleRowCount} property.
 886      * @see #setVisibleRowCount
 887      */
 888     public int getVisibleRowCount() {
 889         return visibleRowCount;
 890     }
 891 
 892     /**
 893      * Sets the {@code visibleRowCount} property, which has different meanings
 894      * depending on the layout orientation: For a {@code VERTICAL} layout
 895      * orientation, this sets the preferred number of rows to display without
 896      * requiring scrolling; for other orientations, it affects the wrapping of
 897      * cells.
 898      * <p>
 899      * In {@code VERTICAL} orientation:<br>
 900      * Setting this property affects the return value of the
 901      * {@link #getPreferredScrollableViewportSize} method, which is used to
 902      * calculate the preferred size of an enclosing viewport. See that method's
 903      * documentation for more details.
 904      * <p>
 905      * In {@code HORIZONTAL_WRAP} and {@code VERTICAL_WRAP} orientations:<br>
 906      * This affects how cells are wrapped. See the documentation of
 907      * {@link #setLayoutOrientation} for more details.
 908      * <p>
 909      * The default value of this property is {@code 8}.
 910      * <p>
 911      * Calling this method with a negative value results in the property
 912      * being set to {@code 0}.
 913      * <p>
 914      * This is a JavaBeans bound property.
 915      *
 916      * @param visibleRowCount  an integer specifying the preferred number of
 917      *                         rows to display without requiring scrolling
 918      * @see #getVisibleRowCount
 919      * @see #getPreferredScrollableViewportSize
 920      * @see #setLayoutOrientation
 921      * @see JComponent#getVisibleRect
 922      * @see JViewport
 923      * @beaninfo
 924      *       bound: true
 925      *   attribute: visualUpdate true
 926      * description: The preferred number of rows to display without
 927      *              requiring scrolling
 928      */
 929     public void setVisibleRowCount(int visibleRowCount) {
 930         int oldValue = this.visibleRowCount;
 931         this.visibleRowCount = Math.max(0, visibleRowCount);
 932         firePropertyChange("visibleRowCount", oldValue, visibleRowCount);
 933     }
 934 
 935 
 936     /**
 937      * Returns the layout orientation property for the list: {@code VERTICAL}
 938      * if the layout is a single column of cells, {@code VERTICAL_WRAP} if the
 939      * layout is "newspaper style" with the content flowing vertically then
 940      * horizontally, or {@code HORIZONTAL_WRAP} if the layout is "newspaper
 941      * style" with the content flowing horizontally then vertically.
 942      *
 943      * @return the value of the {@code layoutOrientation} property
 944      * @see #setLayoutOrientation
 945      * @since 1.4
 946      */
 947     public int getLayoutOrientation() {
 948         return layoutOrientation;
 949     }
 950 
 951 
 952     /**
 953      * Defines the way list cells are layed out. Consider a {@code JList}
 954      * with five cells. Cells can be layed out in one of the following ways:
 955      *
 956      * <pre>
 957      * VERTICAL:          0
 958      *                    1
 959      *                    2
 960      *                    3
 961      *                    4
 962      *
 963      * HORIZONTAL_WRAP:   0  1  2
 964      *                    3  4
 965      *
 966      * VERTICAL_WRAP:     0  3
 967      *                    1  4
 968      *                    2
 969      * </pre>
 970      * <p>
 971      * A description of these layouts follows:
 972      *
 973      * <table border="1"
 974      *  summary="Describes layouts VERTICAL, HORIZONTAL_WRAP, and VERTICAL_WRAP">
 975      *   <tr><th><p style="text-align:left">Value</p></th><th><p style="text-align:left">Description</p></th></tr>
 976      *   <tr><td><code>VERTICAL</code>
 977      *       <td>Cells are layed out vertically in a single column.
 978      *   <tr><td><code>HORIZONTAL_WRAP</code>
 979      *       <td>Cells are layed out horizontally, wrapping to a new row as
 980      *           necessary. If the {@code visibleRowCount} property is less than
 981      *           or equal to zero, wrapping is determined by the width of the
 982      *           list; otherwise wrapping is done in such a way as to ensure
 983      *           {@code visibleRowCount} rows in the list.
 984      *   <tr><td><code>VERTICAL_WRAP</code>
 985      *       <td>Cells are layed out vertically, wrapping to a new column as
 986      *           necessary. If the {@code visibleRowCount} property is less than
 987      *           or equal to zero, wrapping is determined by the height of the
 988      *           list; otherwise wrapping is done at {@code visibleRowCount} rows.
 989      *  </table>
 990      * <p>
 991      * The default value of this property is <code>VERTICAL</code>.
 992      *
 993      * @param layoutOrientation the new layout orientation, one of:
 994      *        {@code VERTICAL}, {@code HORIZONTAL_WRAP} or {@code VERTICAL_WRAP}
 995      * @see #getLayoutOrientation
 996      * @see #setVisibleRowCount
 997      * @see #getScrollableTracksViewportHeight
 998      * @see #getScrollableTracksViewportWidth
 999      * @throws IllegalArgumentException if {@code layoutOrientation} isn't one of the
1000      *         allowable values
1001      * @since 1.4
1002      * @beaninfo
1003      *       bound: true
1004      *   attribute: visualUpdate true
1005      * description: Defines the way list cells are layed out.
1006      *        enum: VERTICAL JList.VERTICAL
1007      *              HORIZONTAL_WRAP JList.HORIZONTAL_WRAP
1008      *              VERTICAL_WRAP JList.VERTICAL_WRAP
1009      */
1010     public void setLayoutOrientation(int layoutOrientation) {
1011         int oldValue = this.layoutOrientation;
1012         switch (layoutOrientation) {
1013         case VERTICAL:
1014         case VERTICAL_WRAP:
1015         case HORIZONTAL_WRAP:
1016             this.layoutOrientation = layoutOrientation;
1017             firePropertyChange("layoutOrientation", oldValue, layoutOrientation);
1018             break;
1019         default:
1020             throw new IllegalArgumentException("layoutOrientation must be one of: VERTICAL, HORIZONTAL_WRAP or VERTICAL_WRAP");
1021         }
1022     }
1023 
1024 
1025     /**
1026      * Returns the smallest list index that is currently visible.
1027      * In a left-to-right {@code componentOrientation}, the first visible
1028      * cell is found closest to the list's upper-left corner. In right-to-left
1029      * orientation, it is found closest to the upper-right corner.
1030      * If nothing is visible or the list is empty, {@code -1} is returned.
1031      * Note that the returned cell may only be partially visible.
1032      *
1033      * @return the index of the first visible cell
1034      * @see #getLastVisibleIndex
1035      * @see JComponent#getVisibleRect
1036      */
1037     public int getFirstVisibleIndex() {
1038         Rectangle r = getVisibleRect();
1039         int first;
1040         if (this.getComponentOrientation().isLeftToRight()) {
1041             first = locationToIndex(r.getLocation());
1042         } else {
1043             first = locationToIndex(new Point((r.x + r.width) - 1, r.y));
1044         }
1045         if (first != -1) {
1046             Rectangle bounds = getCellBounds(first, first);
1047             if (bounds != null) {
1048                 SwingUtilities.computeIntersection(r.x, r.y, r.width, r.height, bounds);
1049                 if (bounds.width == 0 || bounds.height == 0) {
1050                     first = -1;
1051                 }
1052             }
1053         }
1054         return first;
1055     }
1056 
1057 
1058     /**
1059      * Returns the largest list index that is currently visible.
1060      * If nothing is visible or the list is empty, {@code -1} is returned.
1061      * Note that the returned cell may only be partially visible.
1062      *
1063      * @return the index of the last visible cell
1064      * @see #getFirstVisibleIndex
1065      * @see JComponent#getVisibleRect
1066      */
1067     public int getLastVisibleIndex() {
1068         boolean leftToRight = this.getComponentOrientation().isLeftToRight();
1069         Rectangle r = getVisibleRect();
1070         Point lastPoint;
1071         if (leftToRight) {
1072             lastPoint = new Point((r.x + r.width) - 1, (r.y + r.height) - 1);
1073         } else {
1074             lastPoint = new Point(r.x, (r.y + r.height) - 1);
1075         }
1076         int location = locationToIndex(lastPoint);
1077 
1078         if (location != -1) {
1079             Rectangle bounds = getCellBounds(location, location);
1080 
1081             if (bounds != null) {
1082                 SwingUtilities.computeIntersection(r.x, r.y, r.width, r.height, bounds);
1083                 if (bounds.width == 0 || bounds.height == 0) {
1084                     // Try the top left(LTR) or top right(RTL) corner, and
1085                     // then go across checking each cell for HORIZONTAL_WRAP.
1086                     // Try the lower left corner, and then go across checking
1087                     // each cell for other list layout orientation.
1088                     boolean isHorizontalWrap =
1089                         (getLayoutOrientation() == HORIZONTAL_WRAP);
1090                     Point visibleLocation = isHorizontalWrap ?
1091                         new Point(lastPoint.x, r.y) :
1092                         new Point(r.x, lastPoint.y);
1093                     int last;
1094                     int visIndex = -1;
1095                     int lIndex = location;
1096                     location = -1;
1097 
1098                     do {
1099                         last = visIndex;
1100                         visIndex = locationToIndex(visibleLocation);
1101 
1102                         if (visIndex != -1) {
1103                             bounds = getCellBounds(visIndex, visIndex);
1104                             if (visIndex != lIndex && bounds != null &&
1105                                 bounds.contains(visibleLocation)) {
1106                                 location = visIndex;
1107                                 if (isHorizontalWrap) {
1108                                     visibleLocation.y = bounds.y + bounds.height;
1109                                     if (visibleLocation.y >= lastPoint.y) {
1110                                         // Past visible region, bail.
1111                                         last = visIndex;
1112                                     }
1113                                 }
1114                                 else {
1115                                     visibleLocation.x = bounds.x + bounds.width;
1116                                     if (visibleLocation.x >= lastPoint.x) {
1117                                         // Past visible region, bail.
1118                                         last = visIndex;
1119                                     }
1120                                 }
1121 
1122                             }
1123                             else {
1124                                 last = visIndex;
1125                             }
1126                         }
1127                     } while (visIndex != -1 && last != visIndex);
1128                 }
1129             }
1130         }
1131         return location;
1132     }
1133 
1134 
1135     /**
1136      * Scrolls the list within an enclosing viewport to make the specified
1137      * cell completely visible. This calls {@code scrollRectToVisible} with
1138      * the bounds of the specified cell. For this method to work, the
1139      * {@code JList} must be within a <code>JViewport</code>.
1140      * <p>
1141      * If the given index is outside the list's range of cells, this method
1142      * results in nothing.
1143      *
1144      * @param index  the index of the cell to make visible
1145      * @see JComponent#scrollRectToVisible
1146      * @see #getVisibleRect
1147      */
1148     public void ensureIndexIsVisible(int index) {
1149         Rectangle cellBounds = getCellBounds(index, index);
1150         if (cellBounds != null) {
1151             scrollRectToVisible(cellBounds);
1152         }
1153     }
1154 
1155     /**
1156      * Turns on or off automatic drag handling. In order to enable automatic
1157      * drag handling, this property should be set to {@code true}, and the
1158      * list's {@code TransferHandler} needs to be {@code non-null}.
1159      * The default value of the {@code dragEnabled} property is {@code false}.
1160      * <p>
1161      * The job of honoring this property, and recognizing a user drag gesture,
1162      * lies with the look and feel implementation, and in particular, the list's
1163      * {@code ListUI}. When automatic drag handling is enabled, most look and
1164      * feels (including those that subclass {@code BasicLookAndFeel}) begin a
1165      * drag and drop operation whenever the user presses the mouse button over
1166      * an item and then moves the mouse a few pixels. Setting this property to
1167      * {@code true} can therefore have a subtle effect on how selections behave.
1168      * <p>
1169      * If a look and feel is used that ignores this property, you can still
1170      * begin a drag and drop operation by calling {@code exportAsDrag} on the
1171      * list's {@code TransferHandler}.
1172      *
1173      * @param b whether or not to enable automatic drag handling
1174      * @exception HeadlessException if
1175      *            <code>b</code> is <code>true</code> and
1176      *            <code>GraphicsEnvironment.isHeadless()</code>
1177      *            returns <code>true</code>
1178      * @see java.awt.GraphicsEnvironment#isHeadless
1179      * @see #getDragEnabled
1180      * @see #setTransferHandler
1181      * @see TransferHandler
1182      * @since 1.4
1183      *
1184      * @beaninfo
1185      *  description: determines whether automatic drag handling is enabled
1186      *        bound: false
1187      */
1188     public void setDragEnabled(boolean b) {
1189         if (b && GraphicsEnvironment.isHeadless()) {
1190             throw new HeadlessException();
1191         }
1192         dragEnabled = b;
1193     }
1194 
1195     /**
1196      * Returns whether or not automatic drag handling is enabled.
1197      *
1198      * @return the value of the {@code dragEnabled} property
1199      * @see #setDragEnabled
1200      * @since 1.4
1201      */
1202     public boolean getDragEnabled() {
1203         return dragEnabled;
1204     }
1205 
1206     /**
1207      * Sets the drop mode for this component. For backward compatibility,
1208      * the default for this property is <code>DropMode.USE_SELECTION</code>.
1209      * Usage of one of the other modes is recommended, however, for an
1210      * improved user experience. <code>DropMode.ON</code>, for instance,
1211      * offers similar behavior of showing items as selected, but does so without
1212      * affecting the actual selection in the list.
1213      * <p>
1214      * <code>JList</code> supports the following drop modes:
1215      * <ul>
1216      *    <li><code>DropMode.USE_SELECTION</code></li>
1217      *    <li><code>DropMode.ON</code></li>
1218      *    <li><code>DropMode.INSERT</code></li>
1219      *    <li><code>DropMode.ON_OR_INSERT</code></li>
1220      * </ul>
1221      * The drop mode is only meaningful if this component has a
1222      * <code>TransferHandler</code> that accepts drops.
1223      *
1224      * @param dropMode the drop mode to use
1225      * @throws IllegalArgumentException if the drop mode is unsupported
1226      *         or <code>null</code>
1227      * @see #getDropMode
1228      * @see #getDropLocation
1229      * @see #setTransferHandler
1230      * @see TransferHandler
1231      * @since 1.6
1232      */
1233     public final void setDropMode(DropMode dropMode) {
1234         if (dropMode != null) {
1235             switch (dropMode) {
1236                 case USE_SELECTION:
1237                 case ON:
1238                 case INSERT:
1239                 case ON_OR_INSERT:
1240                     this.dropMode = dropMode;
1241                     return;
1242             }
1243         }
1244 
1245         throw new IllegalArgumentException(dropMode + ": Unsupported drop mode for list");
1246     }
1247 
1248     /**
1249      * Returns the drop mode for this component.
1250      *
1251      * @return the drop mode for this component
1252      * @see #setDropMode
1253      * @since 1.6
1254      */
1255     public final DropMode getDropMode() {
1256         return dropMode;
1257     }
1258 
1259     /**
1260      * Calculates a drop location in this component, representing where a
1261      * drop at the given point should insert data.
1262      *
1263      * @param p the point to calculate a drop location for
1264      * @return the drop location, or <code>null</code>
1265      */
1266     DropLocation dropLocationForPoint(Point p) {
1267         DropLocation location = null;
1268         Rectangle rect = null;
1269 
1270         int index = locationToIndex(p);
1271         if (index != -1) {
1272             rect = getCellBounds(index, index);
1273         }
1274 
1275         switch(dropMode) {
1276             case USE_SELECTION:
1277             case ON:
1278                 location = new DropLocation(p,
1279                     (rect != null && rect.contains(p)) ? index : -1,
1280                     false);
1281 
1282                 break;
1283             case INSERT:
1284                 if (index == -1) {
1285                     location = new DropLocation(p, getModel().getSize(), true);
1286                     break;
1287                 }
1288 
1289                 if (layoutOrientation == HORIZONTAL_WRAP) {
1290                     boolean ltr = getComponentOrientation().isLeftToRight();
1291 
1292                     if (SwingUtilities2.liesInHorizontal(rect, p, ltr, false) == TRAILING) {
1293                         index++;
1294                     // special case for below all cells
1295                     } else if (index == getModel().getSize() - 1 && p.y >= rect.y + rect.height) {
1296                         index++;
1297                     }
1298                 } else {
1299                     if (SwingUtilities2.liesInVertical(rect, p, false) == TRAILING) {
1300                         index++;
1301                     }
1302                 }
1303 
1304                 location = new DropLocation(p, index, true);
1305 
1306                 break;
1307             case ON_OR_INSERT:
1308                 if (index == -1) {
1309                     location = new DropLocation(p, getModel().getSize(), true);
1310                     break;
1311                 }
1312 
1313                 boolean between = false;
1314 
1315                 if (layoutOrientation == HORIZONTAL_WRAP) {
1316                     boolean ltr = getComponentOrientation().isLeftToRight();
1317 
1318                     Section section = SwingUtilities2.liesInHorizontal(rect, p, ltr, true);
1319                     if (section == TRAILING) {
1320                         index++;
1321                         between = true;
1322                     // special case for below all cells
1323                     } else if (index == getModel().getSize() - 1 && p.y >= rect.y + rect.height) {
1324                         index++;
1325                         between = true;
1326                     } else if (section == LEADING) {
1327                         between = true;
1328                     }
1329                 } else {
1330                     Section section = SwingUtilities2.liesInVertical(rect, p, true);
1331                     if (section == LEADING) {
1332                         between = true;
1333                     } else if (section == TRAILING) {
1334                         index++;
1335                         between = true;
1336                     }
1337                 }
1338 
1339                 location = new DropLocation(p, index, between);
1340 
1341                 break;
1342             default:
1343                 assert false : "Unexpected drop mode";
1344         }
1345 
1346         return location;
1347     }
1348 
1349     /**
1350      * Called to set or clear the drop location during a DnD operation.
1351      * In some cases, the component may need to use it's internal selection
1352      * temporarily to indicate the drop location. To help facilitate this,
1353      * this method returns and accepts as a parameter a state object.
1354      * This state object can be used to store, and later restore, the selection
1355      * state. Whatever this method returns will be passed back to it in
1356      * future calls, as the state parameter. If it wants the DnD system to
1357      * continue storing the same state, it must pass it back every time.
1358      * Here's how this is used:
1359      * <p>
1360      * Let's say that on the first call to this method the component decides
1361      * to save some state (because it is about to use the selection to show
1362      * a drop index). It can return a state object to the caller encapsulating
1363      * any saved selection state. On a second call, let's say the drop location
1364      * is being changed to something else. The component doesn't need to
1365      * restore anything yet, so it simply passes back the same state object
1366      * to have the DnD system continue storing it. Finally, let's say this
1367      * method is messaged with <code>null</code>. This means DnD
1368      * is finished with this component for now, meaning it should restore
1369      * state. At this point, it can use the state parameter to restore
1370      * said state, and of course return <code>null</code> since there's
1371      * no longer anything to store.
1372      *
1373      * @param location the drop location (as calculated by
1374      *        <code>dropLocationForPoint</code>) or <code>null</code>
1375      *        if there's no longer a valid drop location
1376      * @param state the state object saved earlier for this component,
1377      *        or <code>null</code>
1378      * @param forDrop whether or not the method is being called because an
1379      *        actual drop occurred
1380      * @return any saved state for this component, or <code>null</code> if none
1381      */
1382     Object setDropLocation(TransferHandler.DropLocation location,
1383                            Object state,
1384                            boolean forDrop) {
1385 
1386         Object retVal = null;
1387         DropLocation listLocation = (DropLocation)location;
1388 
1389         if (dropMode == DropMode.USE_SELECTION) {
1390             if (listLocation == null) {
1391                 if (!forDrop && state != null) {
1392                     setSelectedIndices(((int[][])state)[0]);
1393 
1394                     int anchor = ((int[][])state)[1][0];
1395                     int lead = ((int[][])state)[1][1];
1396 
1397                     SwingUtilities2.setLeadAnchorWithoutSelection(
1398                             getSelectionModel(), lead, anchor);
1399                 }
1400             } else {
1401                 if (dropLocation == null) {
1402                     int[] inds = getSelectedIndices();
1403                     retVal = new int[][] {inds, {getAnchorSelectionIndex(),
1404                                                  getLeadSelectionIndex()}};
1405                 } else {
1406                     retVal = state;
1407                 }
1408 
1409                 int index = listLocation.getIndex();
1410                 if (index == -1) {
1411                     clearSelection();
1412                     getSelectionModel().setAnchorSelectionIndex(-1);
1413                     getSelectionModel().setLeadSelectionIndex(-1);
1414                 } else {
1415                     setSelectionInterval(index, index);
1416                 }
1417             }
1418         }
1419 
1420         DropLocation old = dropLocation;
1421         dropLocation = listLocation;
1422         firePropertyChange("dropLocation", old, dropLocation);
1423 
1424         return retVal;
1425     }
1426 
1427     /**
1428      * Returns the location that this component should visually indicate
1429      * as the drop location during a DnD operation over the component,
1430      * or {@code null} if no location is to currently be shown.
1431      * <p>
1432      * This method is not meant for querying the drop location
1433      * from a {@code TransferHandler}, as the drop location is only
1434      * set after the {@code TransferHandler}'s <code>canImport</code>
1435      * has returned and has allowed for the location to be shown.
1436      * <p>
1437      * When this property changes, a property change event with
1438      * name "dropLocation" is fired by the component.
1439      * <p>
1440      * By default, responsibility for listening for changes to this property
1441      * and indicating the drop location visually lies with the list's
1442      * {@code ListUI}, which may paint it directly and/or install a cell
1443      * renderer to do so. Developers wishing to implement custom drop location
1444      * painting and/or replace the default cell renderer, may need to honor
1445      * this property.
1446      *
1447      * @return the drop location
1448      * @see #setDropMode
1449      * @see TransferHandler#canImport(TransferHandler.TransferSupport)
1450      * @since 1.6
1451      */
1452     public final DropLocation getDropLocation() {
1453         return dropLocation;
1454     }
1455 
1456     /**
1457      * Returns the next list element whose {@code toString} value
1458      * starts with the given prefix.
1459      *
1460      * @param prefix the string to test for a match
1461      * @param startIndex the index for starting the search
1462      * @param bias the search direction, either
1463      * Position.Bias.Forward or Position.Bias.Backward.
1464      * @return the index of the next list element that
1465      * starts with the prefix; otherwise {@code -1}
1466      * @exception IllegalArgumentException if prefix is {@code null}
1467      * or startIndex is out of bounds
1468      * @since 1.4
1469      */
1470     public int getNextMatch(String prefix, int startIndex, Position.Bias bias) {
1471         ListModel<E> model = getModel();
1472         int max = model.getSize();
1473         if (prefix == null) {
1474             throw new IllegalArgumentException();
1475         }
1476         if (startIndex < 0 || startIndex >= max) {
1477             throw new IllegalArgumentException();
1478         }
1479         prefix = prefix.toUpperCase();
1480 
1481         // start search from the next element after the selected element
1482         int increment = (bias == Position.Bias.Forward) ? 1 : -1;
1483         int index = startIndex;
1484         do {
1485             E element = model.getElementAt(index);
1486 
1487             if (element != null) {
1488                 String string;
1489 
1490                 if (element instanceof String) {
1491                     string = ((String)element).toUpperCase();
1492                 }
1493                 else {
1494                     string = element.toString();
1495                     if (string != null) {
1496                         string = string.toUpperCase();
1497                     }
1498                 }
1499 
1500                 if (string != null && string.startsWith(prefix)) {
1501                     return index;
1502                 }
1503             }
1504             index = (index + increment + max) % max;
1505         } while (index != startIndex);
1506         return -1;
1507     }
1508 
1509     /**
1510      * Returns the tooltip text to be used for the given event. This overrides
1511      * {@code JComponent}'s {@code getToolTipText} to first check the cell
1512      * renderer component for the cell over which the event occurred, returning
1513      * its tooltip text, if any. This implementation allows you to specify
1514      * tooltip text on the cell level, by using {@code setToolTipText} on your
1515      * cell renderer component.
1516      * <p>
1517      * <strong>Note:</strong> For <code>JList</code> to properly display the
1518      * tooltips of its renderers in this manner, <code>JList</code> must be a
1519      * registered component with the <code>ToolTipManager</code>. This registration
1520      * is done automatically in the constructor. However, if at a later point
1521      * <code>JList</code> is unregistered, by way of a call to
1522      * {@code setToolTipText(null)}, tips from the renderers will no longer display.
1523      *
1524      * @param event the {@code MouseEvent} to fetch the tooltip text for
1525      * @see JComponent#setToolTipText
1526      * @see JComponent#getToolTipText
1527      */
1528     public String getToolTipText(MouseEvent event) {
1529         if(event != null) {
1530             Point p = event.getPoint();
1531             int index = locationToIndex(p);
1532             ListCellRenderer<? super E> r = getCellRenderer();
1533             Rectangle cellBounds;
1534 
1535             if (index != -1 && r != null && (cellBounds =
1536                                getCellBounds(index, index)) != null &&
1537                                cellBounds.contains(p.x, p.y)) {
1538                 ListSelectionModel lsm = getSelectionModel();
1539                 Component rComponent = r.getListCellRendererComponent(
1540                            this, getModel().getElementAt(index), index,
1541                            lsm.isSelectedIndex(index),
1542                            (hasFocus() && (lsm.getLeadSelectionIndex() ==
1543                                            index)));
1544 
1545                 if(rComponent instanceof JComponent) {
1546                     MouseEvent      newEvent;
1547 
1548                     p.translate(-cellBounds.x, -cellBounds.y);
1549                     newEvent = new MouseEvent(rComponent, event.getID(),
1550                                               event.getWhen(),
1551                                               event.getModifiers(),
1552                                               p.x, p.y,
1553                                               event.getXOnScreen(),
1554                                               event.getYOnScreen(),
1555                                               event.getClickCount(),
1556                                               event.isPopupTrigger(),
1557                                               MouseEvent.NOBUTTON);
1558                     MouseEventAccessor meAccessor =
1559                         AWTAccessor.getMouseEventAccessor();
1560                     meAccessor.setCausedByTouchEvent(newEvent,
1561                         meAccessor.isCausedByTouchEvent(event));
1562 
1563                     String tip = ((JComponent)rComponent).getToolTipText(
1564                                               newEvent);
1565 
1566                     if (tip != null) {
1567                         return tip;
1568                     }
1569                 }
1570             }
1571         }
1572         return super.getToolTipText();
1573     }
1574 
1575     /**
1576      * --- ListUI Delegations ---
1577      */
1578 
1579 
1580     /**
1581      * Returns the cell index closest to the given location in the list's
1582      * coordinate system. To determine if the cell actually contains the
1583      * specified location, compare the point against the cell's bounds,
1584      * as provided by {@code getCellBounds}. This method returns {@code -1}
1585      * if the model is empty
1586      * <p>
1587      * This is a cover method that delegates to the method of the same name
1588      * in the list's {@code ListUI}. It returns {@code -1} if the list has
1589      * no {@code ListUI}.
1590      *
1591      * @param location the coordinates of the point
1592      * @return the cell index closest to the given location, or {@code -1}
1593      */
1594     public int locationToIndex(Point location) {
1595         ListUI ui = getUI();
1596         return (ui != null) ? ui.locationToIndex(this, location) : -1;
1597     }
1598 
1599 
1600     /**
1601      * Returns the origin of the specified item in the list's coordinate
1602      * system. This method returns {@code null} if the index isn't valid.
1603      * <p>
1604      * This is a cover method that delegates to the method of the same name
1605      * in the list's {@code ListUI}. It returns {@code null} if the list has
1606      * no {@code ListUI}.
1607      *
1608      * @param index the cell index
1609      * @return the origin of the cell, or {@code null}
1610      */
1611     public Point indexToLocation(int index) {
1612         ListUI ui = getUI();
1613         return (ui != null) ? ui.indexToLocation(this, index) : null;
1614     }
1615 
1616 
1617     /**
1618      * Returns the bounding rectangle, in the list's coordinate system,
1619      * for the range of cells specified by the two indices.
1620      * These indices can be supplied in any order.
1621      * <p>
1622      * If the smaller index is outside the list's range of cells, this method
1623      * returns {@code null}. If the smaller index is valid, but the larger
1624      * index is outside the list's range, the bounds of just the first index
1625      * is returned. Otherwise, the bounds of the valid range is returned.
1626      * <p>
1627      * This is a cover method that delegates to the method of the same name
1628      * in the list's {@code ListUI}. It returns {@code null} if the list has
1629      * no {@code ListUI}.
1630      *
1631      * @param index0 the first index in the range
1632      * @param index1 the second index in the range
1633      * @return the bounding rectangle for the range of cells, or {@code null}
1634      */
1635     public Rectangle getCellBounds(int index0, int index1) {
1636         ListUI ui = getUI();
1637         return (ui != null) ? ui.getCellBounds(this, index0, index1) : null;
1638     }
1639 
1640 
1641     /**
1642      * --- ListModel Support ---
1643      */
1644 
1645 
1646     /**
1647      * Returns the data model that holds the list of items displayed
1648      * by the <code>JList</code> component.
1649      *
1650      * @return the <code>ListModel</code> that provides the displayed
1651      *                          list of items
1652      * @see #setModel
1653      */
1654     public ListModel<E> getModel() {
1655         return dataModel;
1656     }
1657 
1658     /**
1659      * Sets the model that represents the contents or "value" of the
1660      * list, notifies property change listeners, and then clears the
1661      * list's selection.
1662      * <p>
1663      * This is a JavaBeans bound property.
1664      *
1665      * @param model  the <code>ListModel</code> that provides the
1666      *                                          list of items for display
1667      * @exception IllegalArgumentException  if <code>model</code> is
1668      *                                          <code>null</code>
1669      * @see #getModel
1670      * @see #clearSelection
1671      * @beaninfo
1672      *       bound: true
1673      *   attribute: visualUpdate true
1674      * description: The object that contains the data to be drawn by this JList.
1675      */
1676     public void setModel(ListModel<E> model) {
1677         if (model == null) {
1678             throw new IllegalArgumentException("model must be non null");
1679         }
1680         ListModel<E> oldValue = dataModel;
1681         dataModel = model;
1682         firePropertyChange("model", oldValue, dataModel);
1683         clearSelection();
1684     }
1685 
1686 
1687     /**
1688      * Constructs a read-only <code>ListModel</code> from an array of items,
1689      * and calls {@code setModel} with this model.
1690      * <p>
1691      * Attempts to pass a {@code null} value to this method results in
1692      * undefined behavior and, most likely, exceptions. The created model
1693      * references the given array directly. Attempts to modify the array
1694      * after invoking this method results in undefined behavior.
1695      *
1696      * @param listData an array of {@code E} containing the items to
1697      *        display in the list
1698      * @see #setModel
1699      */
1700     public void setListData(final E[] listData) {
1701         setModel (
1702             new AbstractListModel<E>() {
1703                 public int getSize() { return listData.length; }
1704                 public E getElementAt(int i) { return listData[i]; }
1705             }
1706         );
1707     }
1708 
1709 
1710     /**
1711      * Constructs a read-only <code>ListModel</code> from a <code>Vector</code>
1712      * and calls {@code setModel} with this model.
1713      * <p>
1714      * Attempts to pass a {@code null} value to this method results in
1715      * undefined behavior and, most likely, exceptions. The created model
1716      * references the given {@code Vector} directly. Attempts to modify the
1717      * {@code Vector} after invoking this method results in undefined behavior.
1718      *
1719      * @param listData a <code>Vector</code> containing the items to
1720      *                                          display in the list
1721      * @see #setModel
1722      */
1723     public void setListData(final Vector<? extends E> listData) {
1724         setModel (
1725             new AbstractListModel<E>() {
1726                 public int getSize() { return listData.size(); }
1727                 public E getElementAt(int i) { return listData.elementAt(i); }
1728             }
1729         );
1730     }
1731 
1732 
1733     /**
1734      * --- ListSelectionModel delegations and extensions ---
1735      */
1736 
1737 
1738     /**
1739      * Returns an instance of {@code DefaultListSelectionModel}; called
1740      * during construction to initialize the list's selection model
1741      * property.
1742      *
1743      * @return a {@code DefaultListSelecitonModel}, used to initialize
1744      *         the list's selection model property during construction
1745      * @see #setSelectionModel
1746      * @see DefaultListSelectionModel
1747      */
1748     protected ListSelectionModel createSelectionModel() {
1749         return new DefaultListSelectionModel();
1750     }
1751 
1752 
1753     /**
1754      * Returns the current selection model. The selection model maintains the
1755      * selection state of the list. See the class level documentation for more
1756      * details.
1757      *
1758      * @return the <code>ListSelectionModel</code> that maintains the
1759      *         list's selections
1760      *
1761      * @see #setSelectionModel
1762      * @see ListSelectionModel
1763      */
1764     public ListSelectionModel getSelectionModel() {
1765         return selectionModel;
1766     }
1767 
1768 
1769     /**
1770      * Notifies {@code ListSelectionListener}s added directly to the list
1771      * of selection changes made to the selection model. {@code JList}
1772      * listens for changes made to the selection in the selection model,
1773      * and forwards notification to listeners added to the list directly,
1774      * by calling this method.
1775      * <p>
1776      * This method constructs a {@code ListSelectionEvent} with this list
1777      * as the source, and the specified arguments, and sends it to the
1778      * registered {@code ListSelectionListeners}.
1779      *
1780      * @param firstIndex the first index in the range, {@code <= lastIndex}
1781      * @param lastIndex the last index in the range, {@code >= firstIndex}
1782      * @param isAdjusting whether or not this is one in a series of
1783      *        multiple events, where changes are still being made
1784      *
1785      * @see #addListSelectionListener
1786      * @see #removeListSelectionListener
1787      * @see javax.swing.event.ListSelectionEvent
1788      * @see EventListenerList
1789      */
1790     protected void fireSelectionValueChanged(int firstIndex, int lastIndex,
1791                                              boolean isAdjusting)
1792     {
1793         Object[] listeners = listenerList.getListenerList();
1794         ListSelectionEvent e = null;
1795 
1796         for (int i = listeners.length - 2; i >= 0; i -= 2) {
1797             if (listeners[i] == ListSelectionListener.class) {
1798                 if (e == null) {
1799                     e = new ListSelectionEvent(this, firstIndex, lastIndex,
1800                                                isAdjusting);
1801                 }
1802                 ((ListSelectionListener)listeners[i+1]).valueChanged(e);
1803             }
1804         }
1805     }
1806 
1807 
1808     /* A ListSelectionListener that forwards ListSelectionEvents from
1809      * the selectionModel to the JList ListSelectionListeners.  The
1810      * forwarded events only differ from the originals in that their
1811      * source is the JList instead of the selectionModel itself.
1812      */
1813     private class ListSelectionHandler implements ListSelectionListener, Serializable
1814     {
1815         public void valueChanged(ListSelectionEvent e) {
1816             fireSelectionValueChanged(e.getFirstIndex(),
1817                                       e.getLastIndex(),
1818                                       e.getValueIsAdjusting());
1819         }
1820     }
1821 
1822 
1823     /**
1824      * Adds a listener to the list, to be notified each time a change to the
1825      * selection occurs; the preferred way of listening for selection state
1826      * changes. {@code JList} takes care of listening for selection state
1827      * changes in the selection model, and notifies the given listener of
1828      * each change. {@code ListSelectionEvent}s sent to the listener have a
1829      * {@code source} property set to this list.
1830      *
1831      * @param listener the {@code ListSelectionListener} to add
1832      * @see #getSelectionModel
1833      * @see #getListSelectionListeners
1834      */
1835     public void addListSelectionListener(ListSelectionListener listener)
1836     {
1837         if (selectionListener == null) {
1838             selectionListener = new ListSelectionHandler();
1839             getSelectionModel().addListSelectionListener(selectionListener);
1840         }
1841 
1842         listenerList.add(ListSelectionListener.class, listener);
1843     }
1844 
1845 
1846     /**
1847      * Removes a selection listener from the list.
1848      *
1849      * @param listener the {@code ListSelectionListener} to remove
1850      * @see #addListSelectionListener
1851      * @see #getSelectionModel
1852      */
1853     public void removeListSelectionListener(ListSelectionListener listener) {
1854         listenerList.remove(ListSelectionListener.class, listener);
1855     }
1856 
1857 
1858     /**
1859      * Returns an array of all the {@code ListSelectionListener}s added
1860      * to this {@code JList} by way of {@code addListSelectionListener}.
1861      *
1862      * @return all of the {@code ListSelectionListener}s on this list, or
1863      *         an empty array if no listeners have been added
1864      * @see #addListSelectionListener
1865      * @since 1.4
1866      */
1867     public ListSelectionListener[] getListSelectionListeners() {
1868         return listenerList.getListeners(ListSelectionListener.class);
1869     }
1870 
1871 
1872     /**
1873      * Sets the <code>selectionModel</code> for the list to a
1874      * non-<code>null</code> <code>ListSelectionModel</code>
1875      * implementation. The selection model handles the task of making single
1876      * selections, selections of contiguous ranges, and non-contiguous
1877      * selections.
1878      * <p>
1879      * This is a JavaBeans bound property.
1880      *
1881      * @param selectionModel  the <code>ListSelectionModel</code> that
1882      *                          implements the selections
1883      * @exception IllegalArgumentException   if <code>selectionModel</code>
1884      *                                          is <code>null</code>
1885      * @see #getSelectionModel
1886      * @beaninfo
1887      *       bound: true
1888      * description: The selection model, recording which cells are selected.
1889      */
1890     public void setSelectionModel(ListSelectionModel selectionModel) {
1891         if (selectionModel == null) {
1892             throw new IllegalArgumentException("selectionModel must be non null");
1893         }
1894 
1895         /* Remove the forwarding ListSelectionListener from the old
1896          * selectionModel, and add it to the new one, if necessary.
1897          */
1898         if (selectionListener != null) {
1899             this.selectionModel.removeListSelectionListener(selectionListener);
1900             selectionModel.addListSelectionListener(selectionListener);
1901         }
1902 
1903         ListSelectionModel oldValue = this.selectionModel;
1904         this.selectionModel = selectionModel;
1905         firePropertyChange("selectionModel", oldValue, selectionModel);
1906     }
1907 
1908 
1909     /**
1910      * Sets the selection mode for the list. This is a cover method that sets
1911      * the selection mode directly on the selection model.
1912      * <p>
1913      * The following list describes the accepted selection modes:
1914      * <ul>
1915      * <li>{@code ListSelectionModel.SINGLE_SELECTION} -
1916      *   Only one list index can be selected at a time. In this mode,
1917      *   {@code setSelectionInterval} and {@code addSelectionInterval} are
1918      *   equivalent, both replacing the current selection with the index
1919      *   represented by the second argument (the "lead").
1920      * <li>{@code ListSelectionModel.SINGLE_INTERVAL_SELECTION} -
1921      *   Only one contiguous interval can be selected at a time.
1922      *   In this mode, {@code addSelectionInterval} behaves like
1923      *   {@code setSelectionInterval} (replacing the current selection},
1924      *   unless the given interval is immediately adjacent to or overlaps
1925      *   the existing selection, and can be used to grow the selection.
1926      * <li>{@code ListSelectionModel.MULTIPLE_INTERVAL_SELECTION} -
1927      *   In this mode, there's no restriction on what can be selected.
1928      *   This mode is the default.
1929      * </ul>
1930      *
1931      * @param selectionMode the selection mode
1932      * @see #getSelectionMode
1933      * @throws IllegalArgumentException if the selection mode isn't
1934      *         one of those allowed
1935      * @beaninfo
1936      * description: The selection mode.
1937      *        enum: SINGLE_SELECTION            ListSelectionModel.SINGLE_SELECTION
1938      *              SINGLE_INTERVAL_SELECTION   ListSelectionModel.SINGLE_INTERVAL_SELECTION
1939      *              MULTIPLE_INTERVAL_SELECTION ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
1940      */
1941     public void setSelectionMode(int selectionMode) {
1942         getSelectionModel().setSelectionMode(selectionMode);
1943     }
1944 
1945     /**
1946      * Returns the current selection mode for the list. This is a cover
1947      * method that delegates to the method of the same name on the
1948      * list's selection model.
1949      *
1950      * @return the current selection mode
1951      * @see #setSelectionMode
1952      */
1953     public int getSelectionMode() {
1954         return getSelectionModel().getSelectionMode();
1955     }
1956 
1957 
1958     /**
1959      * Returns the anchor selection index. This is a cover method that
1960      * delegates to the method of the same name on the list's selection model.
1961      *
1962      * @return the anchor selection index
1963      * @see ListSelectionModel#getAnchorSelectionIndex
1964      */
1965     public int getAnchorSelectionIndex() {
1966         return getSelectionModel().getAnchorSelectionIndex();
1967     }
1968 
1969 
1970     /**
1971      * Returns the lead selection index. This is a cover method that
1972      * delegates to the method of the same name on the list's selection model.
1973      *
1974      * @return the lead selection index
1975      * @see ListSelectionModel#getLeadSelectionIndex
1976      * @beaninfo
1977      * description: The lead selection index.
1978      */
1979     public int getLeadSelectionIndex() {
1980         return getSelectionModel().getLeadSelectionIndex();
1981     }
1982 
1983 
1984     /**
1985      * Returns the smallest selected cell index, or {@code -1} if the selection
1986      * is empty. This is a cover method that delegates to the method of the same
1987      * name on the list's selection model.
1988      *
1989      * @return the smallest selected cell index, or {@code -1}
1990      * @see ListSelectionModel#getMinSelectionIndex
1991      */
1992     public int getMinSelectionIndex() {
1993         return getSelectionModel().getMinSelectionIndex();
1994     }
1995 
1996 
1997     /**
1998      * Returns the largest selected cell index, or {@code -1} if the selection
1999      * is empty. This is a cover method that delegates to the method of the same
2000      * name on the list's selection model.
2001      *
2002      * @return the largest selected cell index
2003      * @see ListSelectionModel#getMaxSelectionIndex
2004      */
2005     public int getMaxSelectionIndex() {
2006         return getSelectionModel().getMaxSelectionIndex();
2007     }
2008 
2009 
2010     /**
2011      * Returns {@code true} if the specified index is selected,
2012      * else {@code false}. This is a cover method that delegates to the method
2013      * of the same name on the list's selection model.
2014      *
2015      * @param index index to be queried for selection state
2016      * @return {@code true} if the specified index is selected,
2017      *         else {@code false}
2018      * @see ListSelectionModel#isSelectedIndex
2019      * @see #setSelectedIndex
2020      */
2021     public boolean isSelectedIndex(int index) {
2022         return getSelectionModel().isSelectedIndex(index);
2023     }
2024 
2025 
2026     /**
2027      * Returns {@code true} if nothing is selected, else {@code false}.
2028      * This is a cover method that delegates to the method of the same
2029      * name on the list's selection model.
2030      *
2031      * @return {@code true} if nothing is selected, else {@code false}
2032      * @see ListSelectionModel#isSelectionEmpty
2033      * @see #clearSelection
2034      */
2035     public boolean isSelectionEmpty() {
2036         return getSelectionModel().isSelectionEmpty();
2037     }
2038 
2039 
2040     /**
2041      * Clears the selection; after calling this method, {@code isSelectionEmpty}
2042      * will return {@code true}. This is a cover method that delegates to the
2043      * method of the same name on the list's selection model.
2044      *
2045      * @see ListSelectionModel#clearSelection
2046      * @see #isSelectionEmpty
2047      */
2048     public void clearSelection() {
2049         getSelectionModel().clearSelection();
2050     }
2051 
2052 
2053     /**
2054      * Selects the specified interval. Both {@code anchor} and {@code lead}
2055      * indices are included. {@code anchor} doesn't have to be less than or
2056      * equal to {@code lead}. This is a cover method that delegates to the
2057      * method of the same name on the list's selection model.
2058      * <p>
2059      * Refer to the documentation of the selection model class being used
2060      * for details on how values less than {@code 0} are handled.
2061      *
2062      * @param anchor the first index to select
2063      * @param lead the last index to select
2064      * @see ListSelectionModel#setSelectionInterval
2065      * @see DefaultListSelectionModel#setSelectionInterval
2066      * @see #createSelectionModel
2067      * @see #addSelectionInterval
2068      * @see #removeSelectionInterval
2069      */
2070     public void setSelectionInterval(int anchor, int lead) {
2071         getSelectionModel().setSelectionInterval(anchor, lead);
2072     }
2073 
2074 
2075     /**
2076      * Sets the selection to be the union of the specified interval with current
2077      * selection. Both the {@code anchor} and {@code lead} indices are
2078      * included. {@code anchor} doesn't have to be less than or
2079      * equal to {@code lead}. This is a cover method that delegates to the
2080      * method of the same name on the list's selection model.
2081      * <p>
2082      * Refer to the documentation of the selection model class being used
2083      * for details on how values less than {@code 0} are handled.
2084      *
2085      * @param anchor the first index to add to the selection
2086      * @param lead the last index to add to the selection
2087      * @see ListSelectionModel#addSelectionInterval
2088      * @see DefaultListSelectionModel#addSelectionInterval
2089      * @see #createSelectionModel
2090      * @see #setSelectionInterval
2091      * @see #removeSelectionInterval
2092      */
2093     public void addSelectionInterval(int anchor, int lead) {
2094         getSelectionModel().addSelectionInterval(anchor, lead);
2095     }
2096 
2097 
2098     /**
2099      * Sets the selection to be the set difference of the specified interval
2100      * and the current selection. Both the {@code index0} and {@code index1}
2101      * indices are removed. {@code index0} doesn't have to be less than or
2102      * equal to {@code index1}. This is a cover method that delegates to the
2103      * method of the same name on the list's selection model.
2104      * <p>
2105      * Refer to the documentation of the selection model class being used
2106      * for details on how values less than {@code 0} are handled.
2107      *
2108      * @param index0 the first index to remove from the selection
2109      * @param index1 the last index to remove from the selection
2110      * @see ListSelectionModel#removeSelectionInterval
2111      * @see DefaultListSelectionModel#removeSelectionInterval
2112      * @see #createSelectionModel
2113      * @see #setSelectionInterval
2114      * @see #addSelectionInterval
2115      */
2116     public void removeSelectionInterval(int index0, int index1) {
2117         getSelectionModel().removeSelectionInterval(index0, index1);
2118     }
2119 
2120 
2121     /**
2122      * Sets the selection model's {@code valueIsAdjusting} property. When
2123      * {@code true}, upcoming changes to selection should be considered part
2124      * of a single change. This property is used internally and developers
2125      * typically need not call this method. For example, when the model is being
2126      * updated in response to a user drag, the value of the property is set
2127      * to {@code true} when the drag is initiated and set to {@code false}
2128      * when the drag is finished. This allows listeners to update only
2129      * when a change has been finalized, rather than handling all of the
2130      * intermediate values.
2131      * <p>
2132      * You may want to use this directly if making a series of changes
2133      * that should be considered part of a single change.
2134      * <p>
2135      * This is a cover method that delegates to the method of the same name on
2136      * the list's selection model. See the documentation for
2137      * {@link javax.swing.ListSelectionModel#setValueIsAdjusting} for
2138      * more details.
2139      *
2140      * @param b the new value for the property
2141      * @see ListSelectionModel#setValueIsAdjusting
2142      * @see javax.swing.event.ListSelectionEvent#getValueIsAdjusting
2143      * @see #getValueIsAdjusting
2144      */
2145     public void setValueIsAdjusting(boolean b) {
2146         getSelectionModel().setValueIsAdjusting(b);
2147     }
2148 
2149 
2150     /**
2151      * Returns the value of the selection model's {@code isAdjusting} property.
2152      * <p>
2153      * This is a cover method that delegates to the method of the same name on
2154      * the list's selection model.
2155      *
2156      * @return the value of the selection model's {@code isAdjusting} property.
2157      *
2158      * @see #setValueIsAdjusting
2159      * @see ListSelectionModel#getValueIsAdjusting
2160      */
2161     public boolean getValueIsAdjusting() {
2162         return getSelectionModel().getValueIsAdjusting();
2163     }
2164 
2165 
2166     /**
2167      * Returns an array of all of the selected indices, in increasing
2168      * order.
2169      *
2170      * @return all of the selected indices, in increasing order,
2171      *         or an empty array if nothing is selected
2172      * @see #removeSelectionInterval
2173      * @see #addListSelectionListener
2174      */
2175     @Transient
2176     public int[] getSelectedIndices() {
2177         ListSelectionModel sm = getSelectionModel();
2178         int iMin = sm.getMinSelectionIndex();
2179         int iMax = sm.getMaxSelectionIndex();
2180 
2181         if ((iMin < 0) || (iMax < 0)) {
2182             return new int[0];
2183         }
2184 
2185         int[] rvTmp = new int[1+ (iMax - iMin)];
2186         int n = 0;
2187         for(int i = iMin; i <= iMax; i++) {
2188             if (sm.isSelectedIndex(i)) {
2189                 rvTmp[n++] = i;
2190             }
2191         }
2192         int[] rv = new int[n];
2193         System.arraycopy(rvTmp, 0, rv, 0, n);
2194         return rv;
2195     }
2196 
2197 
2198     /**
2199      * Selects a single cell. Does nothing if the given index is greater
2200      * than or equal to the model size. This is a convenience method that uses
2201      * {@code setSelectionInterval} on the selection model. Refer to the
2202      * documentation for the selection model class being used for details on
2203      * how values less than {@code 0} are handled.
2204      *
2205      * @param index the index of the cell to select
2206      * @see ListSelectionModel#setSelectionInterval
2207      * @see #isSelectedIndex
2208      * @see #addListSelectionListener
2209      * @beaninfo
2210      * description: The index of the selected cell.
2211      */
2212     public void setSelectedIndex(int index) {
2213         if (index >= getModel().getSize()) {
2214             return;
2215         }
2216         getSelectionModel().setSelectionInterval(index, index);
2217     }
2218 
2219 
2220     /**
2221      * Changes the selection to be the set of indices specified by the given
2222      * array. Indices greater than or equal to the model size are ignored.
2223      * This is a convenience method that clears the selection and then uses
2224      * {@code addSelectionInterval} on the selection model to add the indices.
2225      * Refer to the documentation of the selection model class being used for
2226      * details on how values less than {@code 0} are handled.
2227      *
2228      * @param indices an array of the indices of the cells to select,
2229      *                {@code non-null}
2230      * @see ListSelectionModel#addSelectionInterval
2231      * @see #isSelectedIndex
2232      * @see #addListSelectionListener
2233      * @throws NullPointerException if the given array is {@code null}
2234      */
2235     public void setSelectedIndices(int[] indices) {
2236         ListSelectionModel sm = getSelectionModel();
2237         sm.clearSelection();
2238         int size = getModel().getSize();
2239         for (int i : indices) {
2240             if (i < size) {
2241                 sm.addSelectionInterval(i, i);
2242             }
2243         }
2244     }
2245 
2246 
2247     /**
2248      * Returns an array of all the selected values, in increasing order based
2249      * on their indices in the list.
2250      *
2251      * @return the selected values, or an empty array if nothing is selected
2252      * @see #isSelectedIndex
2253      * @see #getModel
2254      * @see #addListSelectionListener
2255      *
2256      * @deprecated As of JDK 1.7, replaced by {@link #getSelectedValuesList()}
2257      */
2258     @Deprecated
2259     public Object[] getSelectedValues() {
2260         ListSelectionModel sm = getSelectionModel();
2261         ListModel<E> dm = getModel();
2262 
2263         int iMin = sm.getMinSelectionIndex();
2264         int iMax = sm.getMaxSelectionIndex();
2265 
2266         if ((iMin < 0) || (iMax < 0)) {
2267             return new Object[0];
2268         }
2269 
2270         Object[] rvTmp = new Object[1+ (iMax - iMin)];
2271         int n = 0;
2272         for(int i = iMin; i <= iMax; i++) {
2273             if (sm.isSelectedIndex(i)) {
2274                 rvTmp[n++] = dm.getElementAt(i);
2275             }
2276         }
2277         Object[] rv = new Object[n];
2278         System.arraycopy(rvTmp, 0, rv, 0, n);
2279         return rv;
2280     }
2281 
2282     /**
2283      * Returns a list of all the selected items, in increasing order based
2284      * on their indices in the list.
2285      *
2286      * @return the selected items, or an empty list if nothing is selected
2287      * @see #isSelectedIndex
2288      * @see #getModel
2289      * @see #addListSelectionListener
2290      *
2291      * @since 1.7
2292      */
2293     public List<E> getSelectedValuesList() {
2294         ListSelectionModel sm = getSelectionModel();
2295         ListModel<E> dm = getModel();

2296 
2297         int iMin = sm.getMinSelectionIndex();
2298         int iMax = sm.getMaxSelectionIndex();
2299 
2300         if ((iMin < 0) || (iMax < 0)) {
2301             return Collections.emptyList();
2302         }
2303 
2304         List<E> selectedItems = new ArrayList<E>();
2305         for(int i = iMin; i <= iMax; i++) {
2306             if (sm.isSelectedIndex(i)) {

2307                 selectedItems.add(dm.getElementAt(i));
2308             }
2309         }
2310         return selectedItems;


2311     }
2312 
2313 
2314     /**
2315      * Returns the smallest selected cell index; <i>the selection</i> when only
2316      * a single item is selected in the list. When multiple items are selected,
2317      * it is simply the smallest selected index. Returns {@code -1} if there is
2318      * no selection.
2319      * <p>
2320      * This method is a cover that delegates to {@code getMinSelectionIndex}.
2321      *
2322      * @return the smallest selected cell index
2323      * @see #getMinSelectionIndex
2324      * @see #addListSelectionListener
2325      */
2326     public int getSelectedIndex() {
2327         return getMinSelectionIndex();
2328     }
2329 
2330 
2331     /**
2332      * Returns the value for the smallest selected cell index;
2333      * <i>the selected value</i> when only a single item is selected in the
2334      * list. When multiple items are selected, it is simply the value for the
2335      * smallest selected index. Returns {@code null} if there is no selection.
2336      * <p>
2337      * This is a convenience method that simply returns the model value for
2338      * {@code getMinSelectionIndex}.
2339      *
2340      * @return the first selected value
2341      * @see #getMinSelectionIndex
2342      * @see #getModel
2343      * @see #addListSelectionListener
2344      */
2345     public E getSelectedValue() {
2346         int i = getMinSelectionIndex();
2347         return (i == -1) ? null : getModel().getElementAt(i);
2348     }
2349 
2350 
2351     /**
2352      * Selects the specified object from the list.
2353      *
2354      * @param anObject      the object to select
2355      * @param shouldScroll  {@code true} if the list should scroll to display
2356      *                      the selected object, if one exists; otherwise {@code false}
2357      */
2358     public void setSelectedValue(Object anObject,boolean shouldScroll) {
2359         if(anObject == null)
2360             setSelectedIndex(-1);
2361         else if(!anObject.equals(getSelectedValue())) {
2362             int i,c;
2363             ListModel<E> dm = getModel();
2364             for(i=0,c=dm.getSize();i<c;i++)
2365                 if(anObject.equals(dm.getElementAt(i))){
2366                     setSelectedIndex(i);
2367                     if(shouldScroll)
2368                         ensureIndexIsVisible(i);
2369                     repaint();  /** FIX-ME setSelectedIndex does not redraw all the time with the basic l&f**/
2370                     return;
2371                 }
2372             setSelectedIndex(-1);
2373         }
2374         repaint(); /** FIX-ME setSelectedIndex does not redraw all the time with the basic l&f**/
2375     }
2376 
2377 
2378 
2379     /**
2380      * --- The Scrollable Implementation ---
2381      */
2382 
2383     private void checkScrollableParameters(Rectangle visibleRect, int orientation) {
2384         if (visibleRect == null) {
2385             throw new IllegalArgumentException("visibleRect must be non-null");
2386         }
2387         switch (orientation) {
2388         case SwingConstants.VERTICAL:
2389         case SwingConstants.HORIZONTAL:
2390             break;
2391         default:
2392             throw new IllegalArgumentException("orientation must be one of: VERTICAL, HORIZONTAL");
2393         }
2394     }
2395 
2396 
2397     /**
2398      * Computes the size of viewport needed to display {@code visibleRowCount}
2399      * rows. The value returned by this method depends on the layout
2400      * orientation:
2401      * <p>
2402      * <b>{@code VERTICAL}:</b>
2403      * <br>
2404      * This is trivial if both {@code fixedCellWidth} and {@code fixedCellHeight}
2405      * have been set (either explicitly or by specifying a prototype cell value).
2406      * The width is simply the {@code fixedCellWidth} plus the list's horizontal
2407      * insets. The height is the {@code fixedCellHeight} multiplied by the
2408      * {@code visibleRowCount}, plus the list's vertical insets.
2409      * <p>
2410      * If either {@code fixedCellWidth} or {@code fixedCellHeight} haven't been
2411      * specified, heuristics are used. If the model is empty, the width is
2412      * the {@code fixedCellWidth}, if greater than {@code 0}, or a hard-coded
2413      * value of {@code 256}. The height is the {@code fixedCellHeight} multiplied
2414      * by {@code visibleRowCount}, if {@code fixedCellHeight} is greater than
2415      * {@code 0}, otherwise it is a hard-coded value of {@code 16} multiplied by
2416      * {@code visibleRowCount}.
2417      * <p>
2418      * If the model isn't empty, the width is the preferred size's width,
2419      * typically the width of the widest list element. The height is the
2420      * {@code fixedCellHeight} multiplied by the {@code visibleRowCount},
2421      * plus the list's vertical insets.
2422      * <p>
2423      * <b>{@code VERTICAL_WRAP} or {@code HORIZONTAL_WRAP}:</b>
2424      * <br>
2425      * This method simply returns the value from {@code getPreferredSize}.
2426      * The list's {@code ListUI} is expected to override {@code getPreferredSize}
2427      * to return an appropriate value.
2428      *
2429      * @return a dimension containing the size of the viewport needed
2430      *          to display {@code visibleRowCount} rows
2431      * @see #getPreferredScrollableViewportSize
2432      * @see #setPrototypeCellValue
2433      */
2434     public Dimension getPreferredScrollableViewportSize()
2435     {
2436         if (getLayoutOrientation() != VERTICAL) {
2437             return getPreferredSize();
2438         }
2439         Insets insets = getInsets();
2440         int dx = insets.left + insets.right;
2441         int dy = insets.top + insets.bottom;
2442 
2443         int visibleRowCount = getVisibleRowCount();
2444         int fixedCellWidth = getFixedCellWidth();
2445         int fixedCellHeight = getFixedCellHeight();
2446 
2447         if ((fixedCellWidth > 0) && (fixedCellHeight > 0)) {
2448             int width = fixedCellWidth + dx;
2449             int height = (visibleRowCount * fixedCellHeight) + dy;
2450             return new Dimension(width, height);
2451         }
2452         else if (getModel().getSize() > 0) {
2453             int width = getPreferredSize().width;
2454             int height;
2455             Rectangle r = getCellBounds(0, 0);
2456             if (r != null) {
2457                 height = (visibleRowCount * r.height) + dy;
2458             }
2459             else {
2460                 // Will only happen if UI null, shouldn't matter what we return
2461                 height = 1;
2462             }
2463             return new Dimension(width, height);
2464         }
2465         else {
2466             fixedCellWidth = (fixedCellWidth > 0) ? fixedCellWidth : 256;
2467             fixedCellHeight = (fixedCellHeight > 0) ? fixedCellHeight : 16;
2468             return new Dimension(fixedCellWidth, fixedCellHeight * visibleRowCount);
2469         }
2470     }
2471 
2472 
2473     /**
2474      * Returns the distance to scroll to expose the next or previous
2475      * row (for vertical scrolling) or column (for horizontal scrolling).
2476      * <p>
2477      * For horizontal scrolling, if the layout orientation is {@code VERTICAL},
2478      * then the list's font size is returned (or {@code 1} if the font is
2479      * {@code null}).
2480      *
2481      * @param visibleRect the view area visible within the viewport
2482      * @param orientation {@code SwingConstants.HORIZONTAL} or
2483      *                    {@code SwingConstants.VERTICAL}
2484      * @param direction less or equal to zero to scroll up/back,
2485      *                  greater than zero for down/forward
2486      * @return the "unit" increment for scrolling in the specified direction;
2487      *         always positive
2488      * @see #getScrollableBlockIncrement
2489      * @see Scrollable#getScrollableUnitIncrement
2490      * @throws IllegalArgumentException if {@code visibleRect} is {@code null}, or
2491      *         {@code orientation} isn't one of {@code SwingConstants.VERTICAL} or
2492      *         {@code SwingConstants.HORIZONTAL}
2493      */
2494     public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
2495     {
2496         checkScrollableParameters(visibleRect, orientation);
2497 
2498         if (orientation == SwingConstants.VERTICAL) {
2499             int row = locationToIndex(visibleRect.getLocation());
2500 
2501             if (row == -1) {
2502                 return 0;
2503             }
2504             else {
2505                 /* Scroll Down */
2506                 if (direction > 0) {
2507                     Rectangle r = getCellBounds(row, row);
2508                     return (r == null) ? 0 : r.height - (visibleRect.y - r.y);
2509                 }
2510                 /* Scroll Up */
2511                 else {
2512                     Rectangle r = getCellBounds(row, row);
2513 
2514                     /* The first row is completely visible and it's row 0.
2515                      * We're done.
2516                      */
2517                     if ((r.y == visibleRect.y) && (row == 0))  {
2518                         return 0;
2519                     }
2520                     /* The first row is completely visible, return the
2521                      * height of the previous row or 0 if the first row
2522                      * is the top row of the list.
2523                      */
2524                     else if (r.y == visibleRect.y) {
2525                         Point loc = r.getLocation();
2526                         loc.y--;
2527                         int prevIndex = locationToIndex(loc);
2528                         Rectangle prevR = getCellBounds(prevIndex, prevIndex);
2529 
2530                         if (prevR == null || prevR.y >= r.y) {
2531                             return 0;
2532                         }
2533                         return prevR.height;
2534                     }
2535                     /* The first row is partially visible, return the
2536                      * height of hidden part.
2537                      */
2538                     else {
2539                         return visibleRect.y - r.y;
2540                     }
2541                 }
2542             }
2543         } else if (orientation == SwingConstants.HORIZONTAL &&
2544                            getLayoutOrientation() != JList.VERTICAL) {
2545             boolean leftToRight = getComponentOrientation().isLeftToRight();
2546             int index;
2547             Point leadingPoint;
2548 
2549             if (leftToRight) {
2550                 leadingPoint = visibleRect.getLocation();
2551             }
2552             else {
2553                 leadingPoint = new Point(visibleRect.x + visibleRect.width -1,
2554                                          visibleRect.y);
2555             }
2556             index = locationToIndex(leadingPoint);
2557 
2558             if (index != -1) {
2559                 Rectangle cellBounds = getCellBounds(index, index);
2560                 if (cellBounds != null && cellBounds.contains(leadingPoint)) {
2561                     int leadingVisibleEdge;
2562                     int leadingCellEdge;
2563 
2564                     if (leftToRight) {
2565                         leadingVisibleEdge = visibleRect.x;
2566                         leadingCellEdge = cellBounds.x;
2567                     }
2568                     else {
2569                         leadingVisibleEdge = visibleRect.x + visibleRect.width;
2570                         leadingCellEdge = cellBounds.x + cellBounds.width;
2571                     }
2572 
2573                     if (leadingCellEdge != leadingVisibleEdge) {
2574                         if (direction < 0) {
2575                             // Show remainder of leading cell
2576                             return Math.abs(leadingVisibleEdge - leadingCellEdge);
2577 
2578                         }
2579                         else if (leftToRight) {
2580                             // Hide rest of leading cell
2581                             return leadingCellEdge + cellBounds.width - leadingVisibleEdge;
2582                         }
2583                         else {
2584                             // Hide rest of leading cell
2585                             return leadingVisibleEdge - cellBounds.x;
2586                         }
2587                     }
2588                     // ASSUME: All cells are the same width
2589                     return cellBounds.width;
2590                 }
2591             }
2592         }
2593         Font f = getFont();
2594         return (f != null) ? f.getSize() : 1;
2595     }
2596 
2597 
2598     /**
2599      * Returns the distance to scroll to expose the next or previous block.
2600      * <p>
2601      * For vertical scrolling, the following rules are used:
2602      * <ul>
2603      * <li>if scrolling down, returns the distance to scroll so that the last
2604      * visible element becomes the first completely visible element
2605      * <li>if scrolling up, returns the distance to scroll so that the first
2606      * visible element becomes the last completely visible element
2607      * <li>returns {@code visibleRect.height} if the list is empty
2608      * </ul>
2609      * <p>
2610      * For horizontal scrolling, when the layout orientation is either
2611      * {@code VERTICAL_WRAP} or {@code HORIZONTAL_WRAP}:
2612      * <ul>
2613      * <li>if scrolling right, returns the distance to scroll so that the
2614      * last visible element becomes
2615      * the first completely visible element
2616      * <li>if scrolling left, returns the distance to scroll so that the first
2617      * visible element becomes the last completely visible element
2618      * <li>returns {@code visibleRect.width} if the list is empty
2619      * </ul>
2620      * <p>
2621      * For horizontal scrolling and {@code VERTICAL} orientation,
2622      * returns {@code visibleRect.width}.
2623      * <p>
2624      * Note that the value of {@code visibleRect} must be the equal to
2625      * {@code this.getVisibleRect()}.
2626      *
2627      * @param visibleRect the view area visible within the viewport
2628      * @param orientation {@code SwingConstants.HORIZONTAL} or
2629      *                    {@code SwingConstants.VERTICAL}
2630      * @param direction less or equal to zero to scroll up/back,
2631      *                  greater than zero for down/forward
2632      * @return the "block" increment for scrolling in the specified direction;
2633      *         always positive
2634      * @see #getScrollableUnitIncrement
2635      * @see Scrollable#getScrollableBlockIncrement
2636      * @throws IllegalArgumentException if {@code visibleRect} is {@code null}, or
2637      *         {@code orientation} isn't one of {@code SwingConstants.VERTICAL} or
2638      *         {@code SwingConstants.HORIZONTAL}
2639      */
2640     public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
2641         checkScrollableParameters(visibleRect, orientation);
2642         if (orientation == SwingConstants.VERTICAL) {
2643             int inc = visibleRect.height;
2644             /* Scroll Down */
2645             if (direction > 0) {
2646                 // last cell is the lowest left cell
2647                 int last = locationToIndex(new Point(visibleRect.x, visibleRect.y+visibleRect.height-1));
2648                 if (last != -1) {
2649                     Rectangle lastRect = getCellBounds(last,last);
2650                     if (lastRect != null) {
2651                         inc = lastRect.y - visibleRect.y;
2652                         if ( (inc == 0) && (last < getModel().getSize()-1) ) {
2653                             inc = lastRect.height;
2654                         }
2655                     }
2656                 }
2657             }
2658             /* Scroll Up */
2659             else {
2660                 int newFirst = locationToIndex(new Point(visibleRect.x, visibleRect.y-visibleRect.height));
2661                 int first = getFirstVisibleIndex();
2662                 if (newFirst != -1) {
2663                     if (first == -1) {
2664                         first = locationToIndex(visibleRect.getLocation());
2665                     }
2666                     Rectangle newFirstRect = getCellBounds(newFirst,newFirst);
2667                     Rectangle firstRect = getCellBounds(first,first);
2668                     if ((newFirstRect != null) && (firstRect!=null)) {
2669                         while ( (newFirstRect.y + visibleRect.height <
2670                                  firstRect.y + firstRect.height) &&
2671                                 (newFirstRect.y < firstRect.y) ) {
2672                             newFirst++;
2673                             newFirstRect = getCellBounds(newFirst,newFirst);
2674                         }
2675                         inc = visibleRect.y - newFirstRect.y;
2676                         if ( (inc <= 0) && (newFirstRect.y > 0)) {
2677                             newFirst--;
2678                             newFirstRect = getCellBounds(newFirst,newFirst);
2679                             if (newFirstRect != null) {
2680                                 inc = visibleRect.y - newFirstRect.y;
2681                             }
2682                         }
2683                     }
2684                 }
2685             }
2686             return inc;
2687         }
2688         else if (orientation == SwingConstants.HORIZONTAL &&
2689                  getLayoutOrientation() != JList.VERTICAL) {
2690             boolean leftToRight = getComponentOrientation().isLeftToRight();
2691             int inc = visibleRect.width;
2692             /* Scroll Right (in ltr mode) or Scroll Left (in rtl mode) */
2693             if (direction > 0) {
2694                 // position is upper right if ltr, or upper left otherwise
2695                 int x = visibleRect.x + (leftToRight ? (visibleRect.width - 1) : 0);
2696                 int last = locationToIndex(new Point(x, visibleRect.y));
2697 
2698                 if (last != -1) {
2699                     Rectangle lastRect = getCellBounds(last,last);
2700                     if (lastRect != null) {
2701                         if (leftToRight) {
2702                             inc = lastRect.x - visibleRect.x;
2703                         } else {
2704                             inc = visibleRect.x + visibleRect.width
2705                                       - (lastRect.x + lastRect.width);
2706                         }
2707                         if (inc < 0) {
2708                             inc += lastRect.width;
2709                         } else if ( (inc == 0) && (last < getModel().getSize()-1) ) {
2710                             inc = lastRect.width;
2711                         }
2712                     }
2713                 }
2714             }
2715             /* Scroll Left (in ltr mode) or Scroll Right (in rtl mode) */
2716             else {
2717                 // position is upper left corner of the visibleRect shifted
2718                 // left by the visibleRect.width if ltr, or upper right shifted
2719                 // right by the visibleRect.width otherwise
2720                 int x = visibleRect.x + (leftToRight
2721                                          ? -visibleRect.width
2722                                          : visibleRect.width - 1 + visibleRect.width);
2723                 int first = locationToIndex(new Point(x, visibleRect.y));
2724 
2725                 if (first != -1) {
2726                     Rectangle firstRect = getCellBounds(first,first);
2727                     if (firstRect != null) {
2728                         // the right of the first cell
2729                         int firstRight = firstRect.x + firstRect.width;
2730 
2731                         if (leftToRight) {
2732                             if ((firstRect.x < visibleRect.x - visibleRect.width)
2733                                     && (firstRight < visibleRect.x)) {
2734                                 inc = visibleRect.x - firstRight;
2735                             } else {
2736                                 inc = visibleRect.x - firstRect.x;
2737                             }
2738                         } else {
2739                             int visibleRight = visibleRect.x + visibleRect.width;
2740 
2741                             if ((firstRight > visibleRight + visibleRect.width)
2742                                     && (firstRect.x > visibleRight)) {
2743                                 inc = firstRect.x - visibleRight;
2744                             } else {
2745                                 inc = firstRight - visibleRight;
2746                             }
2747                         }
2748                     }
2749                 }
2750             }
2751             return inc;
2752         }
2753         return visibleRect.width;
2754     }
2755 
2756 
2757     /**
2758      * Returns {@code true} if this {@code JList} is displayed in a
2759      * {@code JViewport} and the viewport is wider than the list's
2760      * preferred width, or if the layout orientation is {@code HORIZONTAL_WRAP}
2761      * and {@code visibleRowCount <= 0}; otherwise returns {@code false}.
2762      * <p>
2763      * If {@code false}, then don't track the viewport's width. This allows
2764      * horizontal scrolling if the {@code JViewport} is itself embedded in a
2765      * {@code JScrollPane}.
2766      *
2767      * @return whether or not an enclosing viewport should force the list's
2768      *         width to match its own
2769      * @see Scrollable#getScrollableTracksViewportWidth
2770      */
2771     public boolean getScrollableTracksViewportWidth() {
2772         if (getLayoutOrientation() == HORIZONTAL_WRAP &&
2773                                       getVisibleRowCount() <= 0) {
2774             return true;
2775         }
2776         Container parent = SwingUtilities.getUnwrappedParent(this);
2777         if (parent instanceof JViewport) {
2778             return parent.getWidth() > getPreferredSize().width;
2779         }
2780         return false;
2781     }
2782 
2783     /**
2784      * Returns {@code true} if this {@code JList} is displayed in a
2785      * {@code JViewport} and the viewport is taller than the list's
2786      * preferred height, or if the layout orientation is {@code VERTICAL_WRAP}
2787      * and {@code visibleRowCount <= 0}; otherwise returns {@code false}.
2788      * <p>
2789      * If {@code false}, then don't track the viewport's height. This allows
2790      * vertical scrolling if the {@code JViewport} is itself embedded in a
2791      * {@code JScrollPane}.
2792      *
2793      * @return whether or not an enclosing viewport should force the list's
2794      *         height to match its own
2795      * @see Scrollable#getScrollableTracksViewportHeight
2796      */
2797     public boolean getScrollableTracksViewportHeight() {
2798         if (getLayoutOrientation() == VERTICAL_WRAP &&
2799                      getVisibleRowCount() <= 0) {
2800             return true;
2801         }
2802         Container parent = SwingUtilities.getUnwrappedParent(this);
2803         if (parent instanceof JViewport) {
2804             return parent.getHeight() > getPreferredSize().height;
2805         }
2806         return false;
2807     }
2808 
2809 
2810     /*
2811      * See {@code readObject} and {@code writeObject} in {@code JComponent}
2812      * for more information about serialization in Swing.
2813      */
2814     private void writeObject(ObjectOutputStream s) throws IOException {
2815         s.defaultWriteObject();
2816         if (getUIClassID().equals(uiClassID)) {
2817             byte count = JComponent.getWriteObjCounter(this);
2818             JComponent.setWriteObjCounter(this, --count);
2819             if (count == 0 && ui != null) {
2820                 ui.installUI(this);
2821             }
2822         }
2823     }
2824 
2825 
2826     /**
2827      * Returns a {@code String} representation of this {@code JList}.
2828      * This method is intended to be used only for debugging purposes,
2829      * and the content and format of the returned {@code String} may vary
2830      * between implementations. The returned {@code String} may be empty,
2831      * but may not be {@code null}.
2832      *
2833      * @return  a {@code String} representation of this {@code JList}.
2834      */
2835     protected String paramString() {
2836         String selectionForegroundString = (selectionForeground != null ?
2837                                             selectionForeground.toString() :
2838                                             "");
2839         String selectionBackgroundString = (selectionBackground != null ?
2840                                             selectionBackground.toString() :
2841                                             "");
2842 
2843         return super.paramString() +
2844         ",fixedCellHeight=" + fixedCellHeight +
2845         ",fixedCellWidth=" + fixedCellWidth +
2846         ",horizontalScrollIncrement=" + horizontalScrollIncrement +
2847         ",selectionBackground=" + selectionBackgroundString +
2848         ",selectionForeground=" + selectionForegroundString +
2849         ",visibleRowCount=" + visibleRowCount +
2850         ",layoutOrientation=" + layoutOrientation;
2851     }
2852 
2853 
2854     /**
2855      * --- Accessibility Support ---
2856      */
2857 
2858     /**
2859      * Gets the {@code AccessibleContext} associated with this {@code JList}.
2860      * For {@code JList}, the {@code AccessibleContext} takes the form of an
2861      * {@code AccessibleJList}.
2862      * <p>
2863      * A new {@code AccessibleJList} instance is created if necessary.
2864      *
2865      * @return an {@code AccessibleJList} that serves as the
2866      *         {@code AccessibleContext} of this {@code JList}
2867      */
2868     public AccessibleContext getAccessibleContext() {
2869         if (accessibleContext == null) {
2870             accessibleContext = new AccessibleJList();
2871         }
2872         return accessibleContext;
2873     }
2874 
2875     /**
2876      * This class implements accessibility support for the
2877      * {@code JList} class. It provides an implementation of the
2878      * Java Accessibility API appropriate to list user-interface
2879      * elements.
2880      * <p>
2881      * <strong>Warning:</strong>
2882      * Serialized objects of this class will not be compatible with
2883      * future Swing releases. The current serialization support is
2884      * appropriate for short term storage or RMI between applications running
2885      * the same version of Swing.  As of 1.4, support for long term storage
2886      * of all JavaBeans&trade;
2887      * has been added to the <code>java.beans</code> package.
2888      * Please see {@link java.beans.XMLEncoder}.
2889      */
2890     protected class AccessibleJList extends AccessibleJComponent
2891         implements AccessibleSelection, PropertyChangeListener,
2892         ListSelectionListener, ListDataListener {
2893 
2894         int leadSelectionIndex;
2895 
2896         public AccessibleJList() {
2897             super();
2898             JList.this.addPropertyChangeListener(this);
2899             JList.this.getSelectionModel().addListSelectionListener(this);
2900             JList.this.getModel().addListDataListener(this);
2901             leadSelectionIndex = JList.this.getLeadSelectionIndex();
2902         }
2903 
2904         /**
2905          * Property Change Listener change method. Used to track changes
2906          * to the DataModel and ListSelectionModel, in order to re-set
2907          * listeners to those for reporting changes there via the Accessibility
2908          * PropertyChange mechanism.
2909          *
2910          * @param e PropertyChangeEvent
2911          */
2912         public void propertyChange(PropertyChangeEvent e) {
2913             String name = e.getPropertyName();
2914             Object oldValue = e.getOldValue();
2915             Object newValue = e.getNewValue();
2916 
2917                 // re-set listData listeners
2918             if (name.compareTo("model") == 0) {
2919 
2920                 if (oldValue != null && oldValue instanceof ListModel) {
2921                     ((ListModel) oldValue).removeListDataListener(this);
2922                 }
2923                 if (newValue != null && newValue instanceof ListModel) {
2924                     ((ListModel) newValue).addListDataListener(this);
2925                 }
2926 
2927                 // re-set listSelectionModel listeners
2928             } else if (name.compareTo("selectionModel") == 0) {
2929 
2930                 if (oldValue != null && oldValue instanceof ListSelectionModel) {
2931                     ((ListSelectionModel) oldValue).removeListSelectionListener(this);
2932                 }
2933                 if (newValue != null && newValue instanceof ListSelectionModel) {
2934                     ((ListSelectionModel) newValue).addListSelectionListener(this);
2935                 }
2936 
2937                 firePropertyChange(
2938                     AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
2939                     Boolean.valueOf(false), Boolean.valueOf(true));
2940             }
2941         }
2942 
2943         /**
2944          * List Selection Listener value change method. Used to fire
2945          * the property change
2946          *
2947          * @param e ListSelectionEvent
2948          *
2949          */
2950         public void valueChanged(ListSelectionEvent e) {
2951             int oldLeadSelectionIndex = leadSelectionIndex;
2952             leadSelectionIndex = JList.this.getLeadSelectionIndex();
2953             if (oldLeadSelectionIndex != leadSelectionIndex) {
2954                 Accessible oldLS, newLS;
2955                 oldLS = (oldLeadSelectionIndex >= 0)
2956                         ? getAccessibleChild(oldLeadSelectionIndex)
2957                         : null;
2958                 newLS = (leadSelectionIndex >= 0)
2959                         ? getAccessibleChild(leadSelectionIndex)
2960                         : null;
2961                 firePropertyChange(AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY,
2962                                    oldLS, newLS);
2963             }
2964 
2965             firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
2966                                Boolean.valueOf(false), Boolean.valueOf(true));
2967             firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
2968                                Boolean.valueOf(false), Boolean.valueOf(true));
2969 
2970             // Process the State changes for Multiselectable
2971             AccessibleStateSet s = getAccessibleStateSet();
2972             ListSelectionModel lsm = JList.this.getSelectionModel();
2973             if (lsm.getSelectionMode() != ListSelectionModel.SINGLE_SELECTION) {
2974                 if (!s.contains(AccessibleState.MULTISELECTABLE)) {
2975                     s.add(AccessibleState.MULTISELECTABLE);
2976                     firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
2977                                        null, AccessibleState.MULTISELECTABLE);
2978                 }
2979             } else {
2980                 if (s.contains(AccessibleState.MULTISELECTABLE)) {
2981                     s.remove(AccessibleState.MULTISELECTABLE);
2982                     firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
2983                                        AccessibleState.MULTISELECTABLE, null);
2984                 }
2985             }
2986         }
2987 
2988         /**
2989          * List Data Listener interval added method. Used to fire the visible data property change
2990          *
2991          * @param e ListDataEvent
2992          *
2993          */
2994         public void intervalAdded(ListDataEvent e) {
2995             firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
2996                                Boolean.valueOf(false), Boolean.valueOf(true));
2997         }
2998 
2999         /**
3000          * List Data Listener interval removed method. Used to fire the visible data property change
3001          *
3002          * @param e ListDataEvent
3003          *
3004          */
3005         public void intervalRemoved(ListDataEvent e) {
3006             firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
3007                                Boolean.valueOf(false), Boolean.valueOf(true));
3008         }
3009 
3010         /**
3011          * List Data Listener contents changed method. Used to fire the visible data property change
3012          *
3013          * @param e ListDataEvent
3014          *
3015          */
3016          public void contentsChanged(ListDataEvent e) {
3017              firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
3018                                 Boolean.valueOf(false), Boolean.valueOf(true));
3019          }
3020 
3021     // AccessibleContext methods
3022 
3023         /**
3024          * Get the state set of this object.
3025          *
3026          * @return an instance of AccessibleState containing the current state
3027          * of the object
3028          * @see AccessibleState
3029          */
3030         public AccessibleStateSet getAccessibleStateSet() {
3031             AccessibleStateSet states = super.getAccessibleStateSet();
3032             if (selectionModel.getSelectionMode() !=
3033                 ListSelectionModel.SINGLE_SELECTION) {
3034                 states.add(AccessibleState.MULTISELECTABLE);
3035             }
3036             return states;
3037         }
3038 
3039         /**
3040          * Get the role of this object.
3041          *
3042          * @return an instance of AccessibleRole describing the role of the
3043          * object
3044          * @see AccessibleRole
3045          */
3046         public AccessibleRole getAccessibleRole() {
3047             return AccessibleRole.LIST;
3048         }
3049 
3050         /**
3051          * Returns the <code>Accessible</code> child contained at
3052          * the local coordinate <code>Point</code>, if one exists.
3053          * Otherwise returns <code>null</code>.
3054          *
3055          * @return the <code>Accessible</code> at the specified
3056          *    location, if it exists
3057          */
3058         public Accessible getAccessibleAt(Point p) {
3059             int i = locationToIndex(p);
3060             if (i >= 0) {
3061                 return new ActionableAccessibleJListChild(JList.this, i);
3062             } else {
3063                 return null;
3064             }
3065         }
3066 
3067         /**
3068          * Returns the number of accessible children in the object.  If all
3069          * of the children of this object implement Accessible, than this
3070          * method should return the number of children of this object.
3071          *
3072          * @return the number of accessible children in the object.
3073          */
3074         public int getAccessibleChildrenCount() {
3075             return getModel().getSize();
3076         }
3077 
3078         /**
3079          * Return the nth Accessible child of the object.
3080          *
3081          * @param i zero-based index of child
3082          * @return the nth Accessible child of the object
3083          */
3084         public Accessible getAccessibleChild(int i) {
3085             if (i >= getModel().getSize()) {
3086                 return null;
3087             } else {
3088                 return new ActionableAccessibleJListChild(JList.this, i);
3089             }
3090         }
3091 
3092         /**
3093          * Get the AccessibleSelection associated with this object.  In the
3094          * implementation of the Java Accessibility API for this class,
3095          * return this object, which is responsible for implementing the
3096          * AccessibleSelection interface on behalf of itself.
3097          *
3098          * @return this object
3099          */
3100         public AccessibleSelection getAccessibleSelection() {
3101             return this;
3102         }
3103 
3104 
3105     // AccessibleSelection methods
3106 
3107         /**
3108          * Returns the number of items currently selected.
3109          * If no items are selected, the return value will be 0.
3110          *
3111          * @return the number of items currently selected.
3112          */
3113          public int getAccessibleSelectionCount() {
3114              return JList.this.getSelectedIndices().length;
3115          }
3116 
3117         /**
3118          * Returns an Accessible representing the specified selected item
3119          * in the object.  If there isn't a selection, or there are
3120          * fewer items selected than the integer passed in, the return
3121          * value will be <code>null</code>.
3122          *
3123          * @param i the zero-based index of selected items
3124          * @return an Accessible containing the selected item
3125          */
3126          public Accessible getAccessibleSelection(int i) {
3127              int len = getAccessibleSelectionCount();
3128              if (i < 0 || i >= len) {
3129                  return null;
3130              } else {
3131                  return getAccessibleChild(JList.this.getSelectedIndices()[i]);
3132              }
3133          }
3134 
3135         /**
3136          * Returns true if the current child of this object is selected.
3137          *
3138          * @param i the zero-based index of the child in this Accessible
3139          * object.
3140          * @see AccessibleContext#getAccessibleChild
3141          */
3142         public boolean isAccessibleChildSelected(int i) {
3143             return isSelectedIndex(i);
3144         }
3145 
3146         /**
3147          * Adds the specified selected item in the object to the object's
3148          * selection.  If the object supports multiple selections,
3149          * the specified item is added to any existing selection, otherwise
3150          * it replaces any existing selection in the object.  If the
3151          * specified item is already selected, this method has no effect.
3152          *
3153          * @param i the zero-based index of selectable items
3154          */
3155          public void addAccessibleSelection(int i) {
3156              JList.this.addSelectionInterval(i, i);
3157          }
3158 
3159         /**
3160          * Removes the specified selected item in the object from the object's
3161          * selection.  If the specified item isn't currently selected, this
3162          * method has no effect.
3163          *
3164          * @param i the zero-based index of selectable items
3165          */
3166          public void removeAccessibleSelection(int i) {
3167              JList.this.removeSelectionInterval(i, i);
3168          }
3169 
3170         /**
3171          * Clears the selection in the object, so that nothing in the
3172          * object is selected.
3173          */
3174          public void clearAccessibleSelection() {
3175              JList.this.clearSelection();
3176          }
3177 
3178         /**
3179          * Causes every selected item in the object to be selected
3180          * if the object supports multiple selections.
3181          */
3182          public void selectAllAccessibleSelection() {
3183              JList.this.addSelectionInterval(0, getAccessibleChildrenCount() -1);
3184          }
3185 
3186           /**
3187            * This class implements accessibility support appropriate
3188            * for list children.
3189            */
3190         protected class AccessibleJListChild extends AccessibleContext
3191                 implements Accessible, AccessibleComponent {
3192             private JList<E>     parent = null;
3193             int indexInParent;
3194             private Component component = null;
3195             private AccessibleContext accessibleContext = null;
3196             private ListModel<E> listModel;
3197             private ListCellRenderer<? super E> cellRenderer = null;
3198 
3199             public AccessibleJListChild(JList<E> parent, int indexInParent) {
3200                 this.parent = parent;
3201                 this.setAccessibleParent(parent);
3202                 this.indexInParent = indexInParent;
3203                 if (parent != null) {
3204                     listModel = parent.getModel();
3205                     cellRenderer = parent.getCellRenderer();
3206                 }
3207             }
3208 
3209             private Component getCurrentComponent() {
3210                 return getComponentAtIndex(indexInParent);
3211             }
3212 
3213             AccessibleContext getCurrentAccessibleContext() {
3214                 Component c = getComponentAtIndex(indexInParent);
3215                 if (c instanceof Accessible) {
3216                     return c.getAccessibleContext();
3217                 } else {
3218                     return null;
3219                 }
3220             }
3221 
3222             private Component getComponentAtIndex(int index) {
3223                 if (index < 0 || index >= listModel.getSize()) {
3224                     return null;
3225                 }
3226                 if ((parent != null)
3227                         && (listModel != null)
3228                         && cellRenderer != null) {
3229                     E value = listModel.getElementAt(index);
3230                     boolean isSelected = parent.isSelectedIndex(index);
3231                     boolean isFocussed = parent.isFocusOwner()
3232                             && (index == parent.getLeadSelectionIndex());
3233                     return cellRenderer.getListCellRendererComponent(
3234                             parent,
3235                             value,
3236                             index,
3237                             isSelected,
3238                             isFocussed);
3239                 } else {
3240                     return null;
3241                 }
3242             }
3243 
3244 
3245             // Accessible Methods
3246            /**
3247             * Get the AccessibleContext for this object. In the
3248             * implementation of the Java Accessibility API for this class,
3249             * returns this object, which is its own AccessibleContext.
3250             *
3251             * @return this object
3252             */
3253             public AccessibleContext getAccessibleContext() {
3254                 return this;
3255             }
3256 
3257 
3258             // AccessibleContext methods
3259 
3260             public String getAccessibleName() {
3261                 AccessibleContext ac = getCurrentAccessibleContext();
3262                 if (ac != null) {
3263                     return ac.getAccessibleName();
3264                 } else {
3265                     return null;
3266                 }
3267             }
3268 
3269             public void setAccessibleName(String s) {
3270                 AccessibleContext ac = getCurrentAccessibleContext();
3271                 if (ac != null) {
3272                     ac.setAccessibleName(s);
3273                 }
3274             }
3275 
3276             public String getAccessibleDescription() {
3277                 AccessibleContext ac = getCurrentAccessibleContext();
3278                 if (ac != null) {
3279                     return ac.getAccessibleDescription();
3280                 } else {
3281                     return null;
3282                 }
3283             }
3284 
3285             public void setAccessibleDescription(String s) {
3286                 AccessibleContext ac = getCurrentAccessibleContext();
3287                 if (ac != null) {
3288                     ac.setAccessibleDescription(s);
3289                 }
3290             }
3291 
3292             public AccessibleRole getAccessibleRole() {
3293                 AccessibleContext ac = getCurrentAccessibleContext();
3294                 if (ac != null) {
3295                     return ac.getAccessibleRole();
3296                 } else {
3297                     return null;
3298                 }
3299             }
3300 
3301             public AccessibleStateSet getAccessibleStateSet() {
3302                 AccessibleContext ac = getCurrentAccessibleContext();
3303                 AccessibleStateSet s;
3304                 if (ac != null) {
3305                     s = ac.getAccessibleStateSet();
3306                 } else {
3307                     s = new AccessibleStateSet();
3308                 }
3309 
3310                 s.add(AccessibleState.SELECTABLE);
3311                 s.add(AccessibleState.VISIBLE);
3312                 if (parent.isFocusOwner()
3313                     && (indexInParent == parent.getLeadSelectionIndex())) {
3314                     s.add(AccessibleState.ACTIVE);
3315                 }
3316                 if (parent.isSelectedIndex(indexInParent)) {
3317                     s.add(AccessibleState.SELECTED);
3318                 }
3319                 if (this.isShowing()) {
3320                     s.add(AccessibleState.SHOWING);
3321                 } else if (s.contains(AccessibleState.SHOWING)) {
3322                     s.remove(AccessibleState.SHOWING);
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            /**
3376             * Get the AccessibleComponent associated with this object.  In the
3377             * implementation of the Java Accessibility API for this class,
3378             * return this object, which is responsible for implementing the
3379             * AccessibleComponent interface on behalf of itself.
3380             *
3381             * @return this object
3382             */
3383             public AccessibleComponent getAccessibleComponent() {
3384                 return this; // to override getBounds()
3385             }
3386 
3387             public AccessibleSelection getAccessibleSelection() {
3388                 AccessibleContext ac = getCurrentAccessibleContext();
3389                 return ac != null ? ac.getAccessibleSelection() : null;
3390             }
3391 
3392             public AccessibleText getAccessibleText() {
3393                 AccessibleContext ac = getCurrentAccessibleContext();
3394                 return ac != null ? ac.getAccessibleText() : null;
3395             }
3396 
3397             public AccessibleValue getAccessibleValue() {
3398                 AccessibleContext ac = getCurrentAccessibleContext();
3399                 return ac != null ? ac.getAccessibleValue() : null;
3400             }
3401 
3402 
3403             // AccessibleComponent methods
3404 
3405             public Color getBackground() {
3406                 AccessibleContext ac = getCurrentAccessibleContext();
3407                 if (ac instanceof AccessibleComponent) {
3408                     return ((AccessibleComponent) ac).getBackground();
3409                 } else {
3410                     Component c = getCurrentComponent();
3411                     if (c != null) {
3412                         return c.getBackground();
3413                     } else {
3414                         return null;
3415                     }
3416                 }
3417             }
3418 
3419             public void setBackground(Color c) {
3420                 AccessibleContext ac = getCurrentAccessibleContext();
3421                 if (ac instanceof AccessibleComponent) {
3422                     ((AccessibleComponent) ac).setBackground(c);
3423                 } else {
3424                     Component cp = getCurrentComponent();
3425                     if (cp != null) {
3426                         cp.setBackground(c);
3427                     }
3428                 }
3429             }
3430 
3431             public Color getForeground() {
3432                 AccessibleContext ac = getCurrentAccessibleContext();
3433                 if (ac instanceof AccessibleComponent) {
3434                     return ((AccessibleComponent) ac).getForeground();
3435                 } else {
3436                     Component c = getCurrentComponent();
3437                     if (c != null) {
3438                         return c.getForeground();
3439                     } else {
3440                         return null;
3441                     }
3442                 }
3443             }
3444 
3445             public void setForeground(Color c) {
3446                 AccessibleContext ac = getCurrentAccessibleContext();
3447                 if (ac instanceof AccessibleComponent) {
3448                     ((AccessibleComponent) ac).setForeground(c);
3449                 } else {
3450                     Component cp = getCurrentComponent();
3451                     if (cp != null) {
3452                         cp.setForeground(c);
3453                     }
3454                 }
3455             }
3456 
3457             public Cursor getCursor() {
3458                 AccessibleContext ac = getCurrentAccessibleContext();
3459                 if (ac instanceof AccessibleComponent) {
3460                     return ((AccessibleComponent) ac).getCursor();
3461                 } else {
3462                     Component c = getCurrentComponent();
3463                     if (c != null) {
3464                         return c.getCursor();
3465                     } else {
3466                         Accessible ap = getAccessibleParent();
3467                         if (ap instanceof AccessibleComponent) {
3468                             return ((AccessibleComponent) ap).getCursor();
3469                         } else {
3470                             return null;
3471                         }
3472                     }
3473                 }
3474             }
3475 
3476             public void setCursor(Cursor c) {
3477                 AccessibleContext ac = getCurrentAccessibleContext();
3478                 if (ac instanceof AccessibleComponent) {
3479                     ((AccessibleComponent) ac).setCursor(c);
3480                 } else {
3481                     Component cp = getCurrentComponent();
3482                     if (cp != null) {
3483                         cp.setCursor(c);
3484                     }
3485                 }
3486             }
3487 
3488             public Font getFont() {
3489                 AccessibleContext ac = getCurrentAccessibleContext();
3490                 if (ac instanceof AccessibleComponent) {
3491                     return ((AccessibleComponent) ac).getFont();
3492                 } else {
3493                     Component c = getCurrentComponent();
3494                     if (c != null) {
3495                         return c.getFont();
3496                     } else {
3497                         return null;
3498                     }
3499                 }
3500             }
3501 
3502             public void setFont(Font f) {
3503                 AccessibleContext ac = getCurrentAccessibleContext();
3504                 if (ac instanceof AccessibleComponent) {
3505                     ((AccessibleComponent) ac).setFont(f);
3506                 } else {
3507                     Component c = getCurrentComponent();
3508                     if (c != null) {
3509                         c.setFont(f);
3510                     }
3511                 }
3512             }
3513 
3514             public FontMetrics getFontMetrics(Font f) {
3515                 AccessibleContext ac = getCurrentAccessibleContext();
3516                 if (ac instanceof AccessibleComponent) {
3517                     return ((AccessibleComponent) ac).getFontMetrics(f);
3518                 } else {
3519                     Component c = getCurrentComponent();
3520                     if (c != null) {
3521                         return c.getFontMetrics(f);
3522                     } else {
3523                         return null;
3524                     }
3525                 }
3526             }
3527 
3528             public boolean isEnabled() {
3529                 AccessibleContext ac = getCurrentAccessibleContext();
3530                 if (ac instanceof AccessibleComponent) {
3531                     return ((AccessibleComponent) ac).isEnabled();
3532                 } else {
3533                     Component c = getCurrentComponent();
3534                     if (c != null) {
3535                         return c.isEnabled();
3536                     } else {
3537                         return false;
3538                     }
3539                 }
3540             }
3541 
3542             public void setEnabled(boolean b) {
3543                 AccessibleContext ac = getCurrentAccessibleContext();
3544                 if (ac instanceof AccessibleComponent) {
3545                     ((AccessibleComponent) ac).setEnabled(b);
3546                 } else {
3547                     Component c = getCurrentComponent();
3548                     if (c != null) {
3549                         c.setEnabled(b);
3550                     }
3551                 }
3552             }
3553 
3554             public boolean isVisible() {
3555                 int fi = parent.getFirstVisibleIndex();
3556                 int li = parent.getLastVisibleIndex();
3557                 // The UI incorrectly returns a -1 for the last
3558                 // visible index if the list is smaller than the
3559                 // viewport size.
3560                 if (li == -1) {
3561                     li = parent.getModel().getSize() - 1;
3562                 }
3563                 return ((indexInParent >= fi)
3564                         && (indexInParent <= li));
3565             }
3566 
3567             public void setVisible(boolean b) {
3568             }
3569 
3570             public boolean isShowing() {
3571                 return (parent.isShowing() && isVisible());
3572             }
3573 
3574             public boolean contains(Point p) {
3575                 AccessibleContext ac = getCurrentAccessibleContext();
3576                 if (ac instanceof AccessibleComponent) {
3577                     Rectangle r = ((AccessibleComponent) ac).getBounds();
3578                     return r.contains(p);
3579                 } else {
3580                     Component c = getCurrentComponent();
3581                     if (c != null) {
3582                         Rectangle r = c.getBounds();
3583                         return r.contains(p);
3584                     } else {
3585                         return getBounds().contains(p);
3586                     }
3587                 }
3588             }
3589 
3590             public Point getLocationOnScreen() {
3591                 if (parent != null) {
3592                     Point listLocation;
3593                     try {
3594                         listLocation = parent.getLocationOnScreen();
3595                     } catch (IllegalComponentStateException e) {
3596                         // This can happen if the component isn't visisble
3597                         return null;
3598                     }
3599                     Point componentLocation = parent.indexToLocation(indexInParent);
3600                     if (componentLocation != null) {
3601                         componentLocation.translate(listLocation.x, listLocation.y);
3602                         return componentLocation;
3603                     } else {
3604                         return null;
3605                     }
3606                 } else {
3607                     return null;
3608                 }
3609             }
3610 
3611             public Point getLocation() {
3612                 if (parent != null) {
3613                     return parent.indexToLocation(indexInParent);
3614                 } else {
3615                     return null;
3616                 }
3617             }
3618 
3619             public void setLocation(Point p) {
3620                 if ((parent != null)  && (parent.contains(p))) {
3621                     ensureIndexIsVisible(indexInParent);
3622                 }
3623             }
3624 
3625             public Rectangle getBounds() {
3626                 if (parent != null) {
3627                     return parent.getCellBounds(indexInParent,indexInParent);
3628                 } else {
3629                     return null;
3630                 }
3631             }
3632 
3633             public void setBounds(Rectangle r) {
3634                 AccessibleContext ac = getCurrentAccessibleContext();
3635                 if (ac instanceof AccessibleComponent) {
3636                     ((AccessibleComponent) ac).setBounds(r);
3637                 }
3638             }
3639 
3640             public Dimension getSize() {
3641                 Rectangle cellBounds = this.getBounds();
3642                 if (cellBounds != null) {
3643                     return cellBounds.getSize();
3644                 } else {
3645                     return null;
3646                 }
3647             }
3648 
3649             public void setSize (Dimension d) {
3650                 AccessibleContext ac = getCurrentAccessibleContext();
3651                 if (ac instanceof AccessibleComponent) {
3652                     ((AccessibleComponent) ac).setSize(d);
3653                 } else {
3654                     Component c = getCurrentComponent();
3655                     if (c != null) {
3656                         c.setSize(d);
3657                     }
3658                 }
3659             }
3660 
3661             public Accessible getAccessibleAt(Point p) {
3662                 AccessibleContext ac = getCurrentAccessibleContext();
3663                 if (ac instanceof AccessibleComponent) {
3664                     return ((AccessibleComponent) ac).getAccessibleAt(p);
3665                 } else {
3666                     return null;
3667                 }
3668             }
3669 
3670             public boolean isFocusTraversable() {
3671                 AccessibleContext ac = getCurrentAccessibleContext();
3672                 if (ac instanceof AccessibleComponent) {
3673                     return ((AccessibleComponent) ac).isFocusTraversable();
3674                 } else {
3675                     Component c = getCurrentComponent();
3676                     if (c != null) {
3677                         return c.isFocusTraversable();
3678                     } else {
3679                         return false;
3680                     }
3681                 }
3682             }
3683 
3684             public void requestFocus() {
3685                 AccessibleContext ac = getCurrentAccessibleContext();
3686                 if (ac instanceof AccessibleComponent) {
3687                     ((AccessibleComponent) ac).requestFocus();
3688                 } else {
3689                     Component c = getCurrentComponent();
3690                     if (c != null) {
3691                         c.requestFocus();
3692                     }
3693                 }
3694             }
3695 
3696             public void addFocusListener(FocusListener l) {
3697                 AccessibleContext ac = getCurrentAccessibleContext();
3698                 if (ac instanceof AccessibleComponent) {
3699                     ((AccessibleComponent) ac).addFocusListener(l);
3700                 } else {
3701                     Component c = getCurrentComponent();
3702                     if (c != null) {
3703                         c.addFocusListener(l);
3704                     }
3705                 }
3706             }
3707 
3708             public void removeFocusListener(FocusListener l) {
3709                 AccessibleContext ac = getCurrentAccessibleContext();
3710                 if (ac instanceof AccessibleComponent) {
3711                     ((AccessibleComponent) ac).removeFocusListener(l);
3712                 } else {
3713                     Component c = getCurrentComponent();
3714                     if (c != null) {
3715                         c.removeFocusListener(l);
3716                     }
3717                 }
3718             }
3719 
3720             // TIGER - 4733624
3721             /**
3722              * Returns the icon for the element renderer, as the only item
3723              * of an array of <code>AccessibleIcon</code>s or a <code>null</code> array
3724              * if the renderer component contains no icons.
3725              *
3726              * @return an array containing the accessible icon
3727              *         or a <code>null</code> array if none
3728              * @since 1.3
3729              */
3730             public AccessibleIcon [] getAccessibleIcon() {
3731                 AccessibleContext ac = getCurrentAccessibleContext();
3732                 if (ac != null) {
3733                     return ac.getAccessibleIcon();
3734                 } else {
3735                     return null;
3736                 }
3737             }
3738 
3739         } // inner class AccessibleJListChild
3740 
3741         private class ActionableAccessibleJListChild
3742             extends AccessibleJListChild
3743             implements AccessibleAction {
3744 
3745             ActionableAccessibleJListChild(JList<E> parent, int indexInParent) {
3746                 super(parent, indexInParent);
3747             }
3748 
3749             @Override
3750             public AccessibleAction getAccessibleAction() {
3751                 AccessibleContext ac = getCurrentAccessibleContext();
3752                 if (ac == null) {
3753                     return null;
3754                 } else {
3755                     AccessibleAction aa = ac.getAccessibleAction();
3756                     if (aa != null) {
3757                         return aa;
3758                     } else {
3759                         return this;
3760                     }
3761                 }
3762             }
3763 
3764             @Override
3765             public boolean doAccessibleAction(int i) {
3766                 if (i == 0) {
3767                     JList.this.setSelectedIndex(indexInParent);
3768                     return true;
3769                 } else {
3770                     return false;
3771                 }
3772             }
3773 
3774             @Override
3775             public String getAccessibleActionDescription(int i) {
3776                 if (i == 0) {
3777                     return UIManager.getString("AbstractButton.clickText");
3778                 } else {
3779                     return null;
3780                 }
3781             }
3782 
3783             @Override
3784             public int getAccessibleActionCount() {
3785                 return 1;
3786             }
3787 
3788         } // inner class ActionableAccessibleJListChild
3789 
3790     } // inner class AccessibleJList
3791 }
--- EOF ---