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