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 class="striped">
 966      * <caption>Describes layouts VERTICAL,HORIZONTAL_WRAP, and VERTICAL_WRAP
 967      * </caption>
 968      * <thead>
 969      *   <tr><th>Value</th><th>Description</th></tr>
 970      * </thead>
 971      * <tbody>
 972      *   <tr><td><code>VERTICAL</code>
 973      *       <td>Cells are layed out vertically in a single column.
 974      *   <tr><td><code>HORIZONTAL_WRAP</code>
 975      *       <td>Cells are layed out horizontally, wrapping to a new row as
 976      *           necessary. If the {@code visibleRowCount} property is less than
 977      *           or equal to zero, wrapping is determined by the width of the
 978      *           list; otherwise wrapping is done in such a way as to ensure
 979      *           {@code visibleRowCount} rows in the list.
 980      *   <tr><td><code>VERTICAL_WRAP</code>
 981      *       <td>Cells are layed out vertically, wrapping to a new column as
 982      *           necessary. If the {@code visibleRowCount} property is less than
 983      *           or equal to zero, wrapping is determined by the height of the
 984      *           list; otherwise wrapping is done at {@code visibleRowCount} rows.
 985      * </tbody>
 986      * </table>
 987      * <p>
 988      * The default value of this property is <code>VERTICAL</code>.
 989      *
 990      * @param layoutOrientation the new layout orientation, one of:
 991      *        {@code VERTICAL}, {@code HORIZONTAL_WRAP} or {@code VERTICAL_WRAP}
 992      * @see #getLayoutOrientation
 993      * @see #setVisibleRowCount
 994      * @see #getScrollableTracksViewportHeight
 995      * @see #getScrollableTracksViewportWidth
 996      * @throws IllegalArgumentException if {@code layoutOrientation} isn't one of the
 997      *         allowable values
 998      * @since 1.4
 999      */
1000     @BeanProperty(visualUpdate = true, enumerationValues = {
1001             "JList.VERTICAL",
1002             "JList.HORIZONTAL_WRAP",
1003             "JList.VERTICAL_WRAP"}, description
1004             = "Defines the way list cells are layed out.")
1005     public void setLayoutOrientation(int layoutOrientation) {
1006         int oldValue = this.layoutOrientation;
1007         switch (layoutOrientation) {
1008         case VERTICAL:
1009         case VERTICAL_WRAP:
1010         case HORIZONTAL_WRAP:
1011             this.layoutOrientation = layoutOrientation;
1012             firePropertyChange("layoutOrientation", oldValue, layoutOrientation);
1013             break;
1014         default:
1015             throw new IllegalArgumentException("layoutOrientation must be one of: VERTICAL, HORIZONTAL_WRAP or VERTICAL_WRAP");
1016         }
1017     }
1018 
1019 
1020     /**
1021      * Returns the smallest list index that is currently visible.
1022      * In a left-to-right {@code componentOrientation}, the first visible
1023      * cell is found closest to the list's upper-left corner. In right-to-left
1024      * orientation, it is found closest to the upper-right corner.
1025      * If nothing is visible or the list is empty, {@code -1} is returned.
1026      * Note that the returned cell may only be partially visible.
1027      *
1028      * @return the index of the first visible cell
1029      * @see #getLastVisibleIndex
1030      * @see JComponent#getVisibleRect
1031      */
1032     @BeanProperty(bound = false)
1033     public int getFirstVisibleIndex() {
1034         Rectangle r = getVisibleRect();
1035         int first;
1036         if (this.getComponentOrientation().isLeftToRight()) {
1037             first = locationToIndex(r.getLocation());
1038         } else {
1039             first = locationToIndex(new Point((r.x + r.width) - 1, r.y));
1040         }
1041         if (first != -1) {
1042             Rectangle bounds = getCellBounds(first, first);
1043             if (bounds != null) {
1044                 SwingUtilities.computeIntersection(r.x, r.y, r.width, r.height, bounds);
1045                 if (bounds.width == 0 || bounds.height == 0) {
1046                     first = -1;
1047                 }
1048             }
1049         }
1050         return first;
1051     }
1052 
1053 
1054     /**
1055      * Returns the largest list index that is currently visible.
1056      * If nothing is visible or the list is empty, {@code -1} is returned.
1057      * Note that the returned cell may only be partially visible.
1058      *
1059      * @return the index of the last visible cell
1060      * @see #getFirstVisibleIndex
1061      * @see JComponent#getVisibleRect
1062      */
1063     @BeanProperty(bound = false)
1064     public int getLastVisibleIndex() {
1065         boolean leftToRight = this.getComponentOrientation().isLeftToRight();
1066         Rectangle r = getVisibleRect();
1067         Point lastPoint;
1068         if (leftToRight) {
1069             lastPoint = new Point((r.x + r.width) - 1, (r.y + r.height) - 1);
1070         } else {
1071             lastPoint = new Point(r.x, (r.y + r.height) - 1);
1072         }
1073         int location = locationToIndex(lastPoint);
1074 
1075         if (location != -1) {
1076             Rectangle bounds = getCellBounds(location, location);
1077 
1078             if (bounds != null) {
1079                 SwingUtilities.computeIntersection(r.x, r.y, r.width, r.height, bounds);
1080                 if (bounds.width == 0 || bounds.height == 0) {
1081                     // Try the top left(LTR) or top right(RTL) corner, and
1082                     // then go across checking each cell for HORIZONTAL_WRAP.
1083                     // Try the lower left corner, and then go across checking
1084                     // each cell for other list layout orientation.
1085                     boolean isHorizontalWrap =
1086                         (getLayoutOrientation() == HORIZONTAL_WRAP);
1087                     Point visibleLocation = isHorizontalWrap ?
1088                         new Point(lastPoint.x, r.y) :
1089                         new Point(r.x, lastPoint.y);
1090                     int last;
1091                     int visIndex = -1;
1092                     int lIndex = location;
1093                     location = -1;
1094 
1095                     do {
1096                         last = visIndex;
1097                         visIndex = locationToIndex(visibleLocation);
1098 
1099                         if (visIndex != -1) {
1100                             bounds = getCellBounds(visIndex, visIndex);
1101                             if (visIndex != lIndex && bounds != null &&
1102                                 bounds.contains(visibleLocation)) {
1103                                 location = visIndex;
1104                                 if (isHorizontalWrap) {
1105                                     visibleLocation.y = bounds.y + bounds.height;
1106                                     if (visibleLocation.y >= lastPoint.y) {
1107                                         // Past visible region, bail.
1108                                         last = visIndex;
1109                                     }
1110                                 }
1111                                 else {
1112                                     visibleLocation.x = bounds.x + bounds.width;
1113                                     if (visibleLocation.x >= lastPoint.x) {
1114                                         // Past visible region, bail.
1115                                         last = visIndex;
1116                                     }
1117                                 }
1118 
1119                             }
1120                             else {
1121                                 last = visIndex;
1122                             }
1123                         }
1124                     } while (visIndex != -1 && last != visIndex);
1125                 }
1126             }
1127         }
1128         return location;
1129     }
1130 
1131 
1132     /**
1133      * Scrolls the list within an enclosing viewport to make the specified
1134      * cell completely visible. This calls {@code scrollRectToVisible} with
1135      * the bounds of the specified cell. For this method to work, the
1136      * {@code JList} must be within a <code>JViewport</code>.
1137      * <p>
1138      * If the given index is outside the list's range of cells, this method
1139      * results in nothing.
1140      *
1141      * @param index  the index of the cell to make visible
1142      * @see JComponent#scrollRectToVisible
1143      * @see #getVisibleRect
1144      */
1145     public void ensureIndexIsVisible(int index) {
1146         Rectangle cellBounds = getCellBounds(index, index);
1147         if (cellBounds != null) {
1148             scrollRectToVisible(cellBounds);
1149         }
1150     }
1151 
1152     /**
1153      * Turns on or off automatic drag handling. In order to enable automatic
1154      * drag handling, this property should be set to {@code true}, and the
1155      * list's {@code TransferHandler} needs to be {@code non-null}.
1156      * The default value of the {@code dragEnabled} property is {@code false}.
1157      * <p>
1158      * The job of honoring this property, and recognizing a user drag gesture,
1159      * lies with the look and feel implementation, and in particular, the list's
1160      * {@code ListUI}. When automatic drag handling is enabled, most look and
1161      * feels (including those that subclass {@code BasicLookAndFeel}) begin a
1162      * drag and drop operation whenever the user presses the mouse button over
1163      * an item and then moves the mouse a few pixels. Setting this property to
1164      * {@code true} can therefore have a subtle effect on how selections behave.
1165      * <p>
1166      * If a look and feel is used that ignores this property, you can still
1167      * begin a drag and drop operation by calling {@code exportAsDrag} on the
1168      * list's {@code TransferHandler}.
1169      *
1170      * @param b whether or not to enable automatic drag handling
1171      * @exception HeadlessException if
1172      *            <code>b</code> is <code>true</code> and
1173      *            <code>GraphicsEnvironment.isHeadless()</code>
1174      *            returns <code>true</code>
1175      * @see java.awt.GraphicsEnvironment#isHeadless
1176      * @see #getDragEnabled
1177      * @see #setTransferHandler
1178      * @see TransferHandler
1179      * @since 1.4
1180      */
1181     @BeanProperty(bound = false, description
1182             = "determines whether automatic drag handling is enabled")
1183     public void setDragEnabled(boolean b) {
1184         if (b && GraphicsEnvironment.isHeadless()) {
1185             throw new HeadlessException();
1186         }
1187         dragEnabled = b;
1188     }
1189 
1190     /**
1191      * Returns whether or not automatic drag handling is enabled.
1192      *
1193      * @return the value of the {@code dragEnabled} property
1194      * @see #setDragEnabled
1195      * @since 1.4
1196      */
1197     public boolean getDragEnabled() {
1198         return dragEnabled;
1199     }
1200 
1201     /**
1202      * Sets the drop mode for this component. For backward compatibility,
1203      * the default for this property is <code>DropMode.USE_SELECTION</code>.
1204      * Usage of one of the other modes is recommended, however, for an
1205      * improved user experience. <code>DropMode.ON</code>, for instance,
1206      * offers similar behavior of showing items as selected, but does so without
1207      * affecting the actual selection in the list.
1208      * <p>
1209      * <code>JList</code> supports the following drop modes:
1210      * <ul>
1211      *    <li><code>DropMode.USE_SELECTION</code></li>
1212      *    <li><code>DropMode.ON</code></li>
1213      *    <li><code>DropMode.INSERT</code></li>
1214      *    <li><code>DropMode.ON_OR_INSERT</code></li>
1215      * </ul>
1216      * The drop mode is only meaningful if this component has a
1217      * <code>TransferHandler</code> that accepts drops.
1218      *
1219      * @param dropMode the drop mode to use
1220      * @throws IllegalArgumentException if the drop mode is unsupported
1221      *         or <code>null</code>
1222      * @see #getDropMode
1223      * @see #getDropLocation
1224      * @see #setTransferHandler
1225      * @see TransferHandler
1226      * @since 1.6
1227      */
1228     public final void setDropMode(DropMode dropMode) {
1229         if (dropMode != null) {
1230             switch (dropMode) {
1231                 case USE_SELECTION:
1232                 case ON:
1233                 case INSERT:
1234                 case ON_OR_INSERT:
1235                     this.dropMode = dropMode;
1236                     return;
1237             }
1238         }
1239 
1240         throw new IllegalArgumentException(dropMode + ": Unsupported drop mode for list");
1241     }
1242 
1243     /**
1244      * Returns the drop mode for this component.
1245      *
1246      * @return the drop mode for this component
1247      * @see #setDropMode
1248      * @since 1.6
1249      */
1250     public final DropMode getDropMode() {
1251         return dropMode;
1252     }
1253 
1254     /**
1255      * Calculates a drop location in this component, representing where a
1256      * drop at the given point should insert data.
1257      *
1258      * @param p the point to calculate a drop location for
1259      * @return the drop location, or <code>null</code>
1260      */
1261     DropLocation dropLocationForPoint(Point p) {
1262         DropLocation location = null;
1263         Rectangle rect = null;
1264 
1265         int index = locationToIndex(p);
1266         if (index != -1) {
1267             rect = getCellBounds(index, index);
1268         }
1269 
1270         switch(dropMode) {
1271             case USE_SELECTION:
1272             case ON:
1273                 location = new DropLocation(p,
1274                     (rect != null && rect.contains(p)) ? index : -1,
1275                     false);
1276 
1277                 break;
1278             case INSERT:
1279                 if (index == -1) {
1280                     location = new DropLocation(p, getModel().getSize(), true);
1281                     break;
1282                 }
1283 
1284                 if (layoutOrientation == HORIZONTAL_WRAP) {
1285                     boolean ltr = getComponentOrientation().isLeftToRight();
1286 
1287                     if (SwingUtilities2.liesInHorizontal(rect, p, ltr, false) == TRAILING) {
1288                         index++;
1289                     // special case for below all cells
1290                     } else if (index == getModel().getSize() - 1 && p.y >= rect.y + rect.height) {
1291                         index++;
1292                     }
1293                 } else {
1294                     if (SwingUtilities2.liesInVertical(rect, p, false) == TRAILING) {
1295                         index++;
1296                     }
1297                 }
1298 
1299                 location = new DropLocation(p, index, true);
1300 
1301                 break;
1302             case ON_OR_INSERT:
1303                 if (index == -1) {
1304                     location = new DropLocation(p, getModel().getSize(), true);
1305                     break;
1306                 }
1307 
1308                 boolean between = false;
1309 
1310                 if (layoutOrientation == HORIZONTAL_WRAP) {
1311                     boolean ltr = getComponentOrientation().isLeftToRight();
1312 
1313                     Section section = SwingUtilities2.liesInHorizontal(rect, p, ltr, true);
1314                     if (section == TRAILING) {
1315                         index++;
1316                         between = true;
1317                     // special case for below all cells
1318                     } else if (index == getModel().getSize() - 1 && p.y >= rect.y + rect.height) {
1319                         index++;
1320                         between = true;
1321                     } else if (section == LEADING) {
1322                         between = true;
1323                     }
1324                 } else {
1325                     Section section = SwingUtilities2.liesInVertical(rect, p, true);
1326                     if (section == LEADING) {
1327                         between = true;
1328                     } else if (section == TRAILING) {
1329                         index++;
1330                         between = true;
1331                     }
1332                 }
1333 
1334                 location = new DropLocation(p, index, between);
1335 
1336                 break;
1337             default:
1338                 assert false : "Unexpected drop mode";
1339         }
1340 
1341         return location;
1342     }
1343 
1344     /**
1345      * Called to set or clear the drop location during a DnD operation.
1346      * In some cases, the component may need to use it's internal selection
1347      * temporarily to indicate the drop location. To help facilitate this,
1348      * this method returns and accepts as a parameter a state object.
1349      * This state object can be used to store, and later restore, the selection
1350      * state. Whatever this method returns will be passed back to it in
1351      * future calls, as the state parameter. If it wants the DnD system to
1352      * continue storing the same state, it must pass it back every time.
1353      * Here's how this is used:
1354      * <p>
1355      * Let's say that on the first call to this method the component decides
1356      * to save some state (because it is about to use the selection to show
1357      * a drop index). It can return a state object to the caller encapsulating
1358      * any saved selection state. On a second call, let's say the drop location
1359      * is being changed to something else. The component doesn't need to
1360      * restore anything yet, so it simply passes back the same state object
1361      * to have the DnD system continue storing it. Finally, let's say this
1362      * method is messaged with <code>null</code>. This means DnD
1363      * is finished with this component for now, meaning it should restore
1364      * state. At this point, it can use the state parameter to restore
1365      * said state, and of course return <code>null</code> since there's
1366      * no longer anything to store.
1367      *
1368      * @param location the drop location (as calculated by
1369      *        <code>dropLocationForPoint</code>) or <code>null</code>
1370      *        if there's no longer a valid drop location
1371      * @param state the state object saved earlier for this component,
1372      *        or <code>null</code>
1373      * @param forDrop whether or not the method is being called because an
1374      *        actual drop occurred
1375      * @return any saved state for this component, or <code>null</code> if none
1376      */
1377     Object setDropLocation(TransferHandler.DropLocation location,
1378                            Object state,
1379                            boolean forDrop) {
1380 
1381         Object retVal = null;
1382         DropLocation listLocation = (DropLocation)location;
1383 
1384         if (dropMode == DropMode.USE_SELECTION) {
1385             if (listLocation == null) {
1386                 if (!forDrop && state != null) {
1387                     setSelectedIndices(((int[][])state)[0]);
1388 
1389                     int anchor = ((int[][])state)[1][0];
1390                     int lead = ((int[][])state)[1][1];
1391 
1392                     SwingUtilities2.setLeadAnchorWithoutSelection(
1393                             getSelectionModel(), lead, anchor);
1394                 }
1395             } else {
1396                 if (dropLocation == null) {
1397                     int[] inds = getSelectedIndices();
1398                     retVal = new int[][] {inds, {getAnchorSelectionIndex(),
1399                                                  getLeadSelectionIndex()}};
1400                 } else {
1401                     retVal = state;
1402                 }
1403 
1404                 int index = listLocation.getIndex();
1405                 if (index == -1) {
1406                     clearSelection();
1407                     getSelectionModel().setAnchorSelectionIndex(-1);
1408                     getSelectionModel().setLeadSelectionIndex(-1);
1409                 } else {
1410                     setSelectionInterval(index, index);
1411                 }
1412             }
1413         }
1414 
1415         DropLocation old = dropLocation;
1416         dropLocation = listLocation;
1417         firePropertyChange("dropLocation", old, dropLocation);
1418 
1419         return retVal;
1420     }
1421 
1422     /**
1423      * Returns the location that this component should visually indicate
1424      * as the drop location during a DnD operation over the component,
1425      * or {@code null} if no location is to currently be shown.
1426      * <p>
1427      * This method is not meant for querying the drop location
1428      * from a {@code TransferHandler}, as the drop location is only
1429      * set after the {@code TransferHandler}'s <code>canImport</code>
1430      * has returned and has allowed for the location to be shown.
1431      * <p>
1432      * When this property changes, a property change event with
1433      * name "dropLocation" is fired by the component.
1434      * <p>
1435      * By default, responsibility for listening for changes to this property
1436      * and indicating the drop location visually lies with the list's
1437      * {@code ListUI}, which may paint it directly and/or install a cell
1438      * renderer to do so. Developers wishing to implement custom drop location
1439      * painting and/or replace the default cell renderer, may need to honor
1440      * this property.
1441      *
1442      * @return the drop location
1443      * @see #setDropMode
1444      * @see TransferHandler#canImport(TransferHandler.TransferSupport)
1445      * @since 1.6
1446      */
1447     @BeanProperty(bound = false)
1448     public final DropLocation getDropLocation() {
1449         return dropLocation;
1450     }
1451 
1452     /**
1453      * Returns the next list element whose {@code toString} value
1454      * starts with the given prefix.
1455      *
1456      * @param prefix the string to test for a match
1457      * @param startIndex the index for starting the search
1458      * @param bias the search direction, either
1459      * Position.Bias.Forward or Position.Bias.Backward.
1460      * @return the index of the next list element that
1461      * starts with the prefix; otherwise {@code -1}
1462      * @exception IllegalArgumentException if prefix is {@code null}
1463      * or startIndex is out of bounds
1464      * @since 1.4
1465      */
1466     public int getNextMatch(String prefix, int startIndex, Position.Bias bias) {
1467         ListModel<E> model = getModel();
1468         int max = model.getSize();
1469         if (prefix == null) {
1470             throw new IllegalArgumentException();
1471         }
1472         if (startIndex < 0 || startIndex >= max) {
1473             throw new IllegalArgumentException();
1474         }
1475         prefix = prefix.toUpperCase();
1476 
1477         // start search from the next element after the selected element
1478         int increment = (bias == Position.Bias.Forward) ? 1 : -1;
1479         int index = startIndex;
1480         do {
1481             E element = model.getElementAt(index);
1482 
1483             if (element != null) {
1484                 String string;
1485 
1486                 if (element instanceof String) {
1487                     string = ((String)element).toUpperCase();
1488                 }
1489                 else {
1490                     string = element.toString();
1491                     if (string != null) {
1492                         string = string.toUpperCase();
1493                     }
1494                 }
1495 
1496                 if (string != null && string.startsWith(prefix)) {
1497                     return index;
1498                 }
1499             }
1500             index = (index + increment + max) % max;
1501         } while (index != startIndex);
1502         return -1;
1503     }
1504 
1505     /**
1506      * Returns the tooltip text to be used for the given event. This overrides
1507      * {@code JComponent}'s {@code getToolTipText} to first check the cell
1508      * renderer component for the cell over which the event occurred, returning
1509      * its tooltip text, if any. This implementation allows you to specify
1510      * tooltip text on the cell level, by using {@code setToolTipText} on your
1511      * cell renderer component.
1512      * <p>
1513      * <strong>Note:</strong> For <code>JList</code> to properly display the
1514      * tooltips of its renderers in this manner, <code>JList</code> must be a
1515      * registered component with the <code>ToolTipManager</code>. This registration
1516      * is done automatically in the constructor. However, if at a later point
1517      * <code>JList</code> is unregistered, by way of a call to
1518      * {@code setToolTipText(null)}, tips from the renderers will no longer display.
1519      *
1520      * @param event the {@code MouseEvent} to fetch the tooltip text for
1521      * @see JComponent#setToolTipText
1522      * @see JComponent#getToolTipText
1523      */
1524     @SuppressWarnings("deprecation")
1525     public String getToolTipText(MouseEvent event) {
1526         if(event != null) {
1527             Point p = event.getPoint();
1528             int index = locationToIndex(p);
1529             ListCellRenderer<? super E> r = getCellRenderer();
1530             Rectangle cellBounds;
1531 
1532             if (index != -1 && r != null && (cellBounds =
1533                                getCellBounds(index, index)) != null &&
1534                                cellBounds.contains(p.x, p.y)) {
1535                 ListSelectionModel lsm = getSelectionModel();
1536                 Component rComponent = r.getListCellRendererComponent(
1537                            this, getModel().getElementAt(index), index,
1538                            lsm.isSelectedIndex(index),
1539                            (hasFocus() && (lsm.getLeadSelectionIndex() ==
1540                                            index)));
1541 
1542                 if(rComponent instanceof JComponent) {
1543                     MouseEvent      newEvent;
1544 
1545                     p.translate(-cellBounds.x, -cellBounds.y);
1546                     newEvent = new MouseEvent(rComponent, event.getID(),
1547                                               event.getWhen(),
1548                                               event.getModifiers(),
1549                                               p.x, p.y,
1550                                               event.getXOnScreen(),
1551                                               event.getYOnScreen(),
1552                                               event.getClickCount(),
1553                                               event.isPopupTrigger(),
1554                                               MouseEvent.NOBUTTON);
1555 
1556                     String tip = ((JComponent)rComponent).getToolTipText(
1557                                               newEvent);
1558 
1559                     if (tip != null) {
1560                         return tip;
1561                     }
1562                 }
1563             }
1564         }
1565         return super.getToolTipText();
1566     }
1567 
1568     /**
1569      * --- ListUI Delegations ---
1570      */
1571 
1572 
1573     /**
1574      * Returns the cell index closest to the given location in the list's
1575      * coordinate system. To determine if the cell actually contains the
1576      * specified location, compare the point against the cell's bounds,
1577      * as provided by {@code getCellBounds}. This method returns {@code -1}
1578      * if the model is empty
1579      * <p>
1580      * This is a cover method that delegates to the method of the same name
1581      * in the list's {@code ListUI}. It returns {@code -1} if the list has
1582      * no {@code ListUI}.
1583      *
1584      * @param location the coordinates of the point
1585      * @return the cell index closest to the given location, or {@code -1}
1586      */
1587     public int locationToIndex(Point location) {
1588         ListUI ui = getUI();
1589         return (ui != null) ? ui.locationToIndex(this, location) : -1;
1590     }
1591 
1592 
1593     /**
1594      * Returns the origin of the specified item in the list's coordinate
1595      * system. This method returns {@code null} if the index isn't valid.
1596      * <p>
1597      * This is a cover method that delegates to the method of the same name
1598      * in the list's {@code ListUI}. It returns {@code null} if the list has
1599      * no {@code ListUI}.
1600      *
1601      * @param index the cell index
1602      * @return the origin of the cell, or {@code null}
1603      */
1604     public Point indexToLocation(int index) {
1605         ListUI ui = getUI();
1606         return (ui != null) ? ui.indexToLocation(this, index) : null;
1607     }
1608 
1609 
1610     /**
1611      * Returns the bounding rectangle, in the list's coordinate system,
1612      * for the range of cells specified by the two indices.
1613      * These indices can be supplied in any order.
1614      * <p>
1615      * If the smaller index is outside the list's range of cells, this method
1616      * returns {@code null}. If the smaller index is valid, but the larger
1617      * index is outside the list's range, the bounds of just the first index
1618      * is returned. Otherwise, the bounds of the valid range is returned.
1619      * <p>
1620      * This is a cover method that delegates to the method of the same name
1621      * in the list's {@code ListUI}. It returns {@code null} if the list has
1622      * no {@code ListUI}.
1623      *
1624      * @param index0 the first index in the range
1625      * @param index1 the second index in the range
1626      * @return the bounding rectangle for the range of cells, or {@code null}
1627      */
1628     public Rectangle getCellBounds(int index0, int index1) {
1629         ListUI ui = getUI();
1630         return (ui != null) ? ui.getCellBounds(this, index0, index1) : null;
1631     }
1632 
1633 
1634     /**
1635      * --- ListModel Support ---
1636      */
1637 
1638 
1639     /**
1640      * Returns the data model that holds the list of items displayed
1641      * by the <code>JList</code> component.
1642      *
1643      * @return the <code>ListModel</code> that provides the displayed
1644      *                          list of items
1645      * @see #setModel
1646      */
1647     public ListModel<E> getModel() {
1648         return dataModel;
1649     }
1650 
1651     /**
1652      * Sets the model that represents the contents or "value" of the
1653      * list, notifies property change listeners, and then clears the
1654      * list's selection.
1655      * <p>
1656      * This is a JavaBeans bound property.
1657      *
1658      * @param model  the <code>ListModel</code> that provides the
1659      *                                          list of items for display
1660      * @exception IllegalArgumentException  if <code>model</code> is
1661      *                                          <code>null</code>
1662      * @see #getModel
1663      * @see #clearSelection
1664      */
1665     @BeanProperty(visualUpdate = true, description
1666             = "The object that contains the data to be drawn by this JList.")
1667     public void setModel(ListModel<E> model) {
1668         if (model == null) {
1669             throw new IllegalArgumentException("model must be non null");
1670         }
1671         ListModel<E> oldValue = dataModel;
1672         dataModel = model;
1673         firePropertyChange("model", oldValue, dataModel);
1674         clearSelection();
1675     }
1676 
1677 
1678     /**
1679      * Constructs a read-only <code>ListModel</code> from an array of items,
1680      * and calls {@code setModel} with this model.
1681      * <p>
1682      * Attempts to pass a {@code null} value to this method results in
1683      * undefined behavior and, most likely, exceptions. The created model
1684      * references the given array directly. Attempts to modify the array
1685      * after invoking this method results in undefined behavior.
1686      *
1687      * @param listData an array of {@code E} containing the items to
1688      *        display in the list
1689      * @see #setModel
1690      */
1691     public void setListData(final E[] listData) {
1692         setModel (
1693             new AbstractListModel<E>() {
1694                 public int getSize() { return listData.length; }
1695                 public E getElementAt(int i) { return listData[i]; }
1696             }
1697         );
1698     }
1699 
1700 
1701     /**
1702      * Constructs a read-only <code>ListModel</code> from a <code>Vector</code>
1703      * and calls {@code setModel} with this model.
1704      * <p>
1705      * Attempts to pass a {@code null} value to this method results in
1706      * undefined behavior and, most likely, exceptions. The created model
1707      * references the given {@code Vector} directly. Attempts to modify the
1708      * {@code Vector} after invoking this method results in undefined behavior.
1709      *
1710      * @param listData a <code>Vector</code> containing the items to
1711      *                                          display in the list
1712      * @see #setModel
1713      */
1714     public void setListData(final Vector<? extends E> listData) {
1715         setModel (
1716             new AbstractListModel<E>() {
1717                 public int getSize() { return listData.size(); }
1718                 public E getElementAt(int i) { return listData.elementAt(i); }
1719             }
1720         );
1721     }
1722 
1723 
1724     /**
1725      * --- ListSelectionModel delegations and extensions ---
1726      */
1727 
1728 
1729     /**
1730      * Returns an instance of {@code DefaultListSelectionModel}; called
1731      * during construction to initialize the list's selection model
1732      * property.
1733      *
1734      * @return a {@code DefaultListSelecitonModel}, used to initialize
1735      *         the list's selection model property during construction
1736      * @see #setSelectionModel
1737      * @see DefaultListSelectionModel
1738      */
1739     protected ListSelectionModel createSelectionModel() {
1740         return new DefaultListSelectionModel();
1741     }
1742 
1743 
1744     /**
1745      * Returns the current selection model. The selection model maintains the
1746      * selection state of the list. See the class level documentation for more
1747      * details.
1748      *
1749      * @return the <code>ListSelectionModel</code> that maintains the
1750      *         list's selections
1751      *
1752      * @see #setSelectionModel
1753      * @see ListSelectionModel
1754      */
1755     public ListSelectionModel getSelectionModel() {
1756         return selectionModel;
1757     }
1758 
1759 
1760     /**
1761      * Notifies {@code ListSelectionListener}s added directly to the list
1762      * of selection changes made to the selection model. {@code JList}
1763      * listens for changes made to the selection in the selection model,
1764      * and forwards notification to listeners added to the list directly,
1765      * by calling this method.
1766      * <p>
1767      * This method constructs a {@code ListSelectionEvent} with this list
1768      * as the source, and the specified arguments, and sends it to the
1769      * registered {@code ListSelectionListeners}.
1770      *
1771      * @param firstIndex the first index in the range, {@code <= lastIndex}
1772      * @param lastIndex the last index in the range, {@code >= firstIndex}
1773      * @param isAdjusting whether or not this is one in a series of
1774      *        multiple events, where changes are still being made
1775      *
1776      * @see #addListSelectionListener
1777      * @see #removeListSelectionListener
1778      * @see javax.swing.event.ListSelectionEvent
1779      * @see EventListenerList
1780      */
1781     protected void fireSelectionValueChanged(int firstIndex, int lastIndex,
1782                                              boolean isAdjusting)
1783     {
1784         Object[] listeners = listenerList.getListenerList();
1785         ListSelectionEvent e = null;
1786 
1787         for (int i = listeners.length - 2; i >= 0; i -= 2) {
1788             if (listeners[i] == ListSelectionListener.class) {
1789                 if (e == null) {
1790                     e = new ListSelectionEvent(this, firstIndex, lastIndex,
1791                                                isAdjusting);
1792                 }
1793                 ((ListSelectionListener)listeners[i+1]).valueChanged(e);
1794             }
1795         }
1796     }
1797 
1798 
1799     /* A ListSelectionListener that forwards ListSelectionEvents from
1800      * the selectionModel to the JList ListSelectionListeners.  The
1801      * forwarded events only differ from the originals in that their
1802      * source is the JList instead of the selectionModel itself.
1803      */
1804     private class ListSelectionHandler implements ListSelectionListener, Serializable
1805     {
1806         public void valueChanged(ListSelectionEvent e) {
1807             fireSelectionValueChanged(e.getFirstIndex(),
1808                                       e.getLastIndex(),
1809                                       e.getValueIsAdjusting());
1810         }
1811     }
1812 
1813 
1814     /**
1815      * Adds a listener to the list, to be notified each time a change to the
1816      * selection occurs; the preferred way of listening for selection state
1817      * changes. {@code JList} takes care of listening for selection state
1818      * changes in the selection model, and notifies the given listener of
1819      * each change. {@code ListSelectionEvent}s sent to the listener have a
1820      * {@code source} property set to this list.
1821      *
1822      * @param listener the {@code ListSelectionListener} to add
1823      * @see #getSelectionModel
1824      * @see #getListSelectionListeners
1825      */
1826     public void addListSelectionListener(ListSelectionListener listener)
1827     {
1828         if (selectionListener == null) {
1829             selectionListener = new ListSelectionHandler();
1830             getSelectionModel().addListSelectionListener(selectionListener);
1831         }
1832 
1833         listenerList.add(ListSelectionListener.class, listener);
1834     }
1835 
1836 
1837     /**
1838      * Removes a selection listener from the list.
1839      *
1840      * @param listener the {@code ListSelectionListener} to remove
1841      * @see #addListSelectionListener
1842      * @see #getSelectionModel
1843      */
1844     public void removeListSelectionListener(ListSelectionListener listener) {
1845         listenerList.remove(ListSelectionListener.class, listener);
1846     }
1847 
1848 
1849     /**
1850      * Returns an array of all the {@code ListSelectionListener}s added
1851      * to this {@code JList} by way of {@code addListSelectionListener}.
1852      *
1853      * @return all of the {@code ListSelectionListener}s on this list, or
1854      *         an empty array if no listeners have been added
1855      * @see #addListSelectionListener
1856      * @since 1.4
1857      */
1858     @BeanProperty(bound = false)
1859     public ListSelectionListener[] getListSelectionListeners() {
1860         return listenerList.getListeners(ListSelectionListener.class);
1861     }
1862 
1863 
1864     /**
1865      * Sets the <code>selectionModel</code> for the list to a
1866      * non-<code>null</code> <code>ListSelectionModel</code>
1867      * implementation. The selection model handles the task of making single
1868      * selections, selections of contiguous ranges, and non-contiguous
1869      * selections.
1870      * <p>
1871      * This is a JavaBeans bound property.
1872      *
1873      * @param selectionModel  the <code>ListSelectionModel</code> that
1874      *                          implements the selections
1875      * @exception IllegalArgumentException   if <code>selectionModel</code>
1876      *                                          is <code>null</code>
1877      * @see #getSelectionModel
1878      */
1879     @BeanProperty(description
1880             = "The selection model, recording which cells are selected.")
1881     public void setSelectionModel(ListSelectionModel selectionModel) {
1882         if (selectionModel == null) {
1883             throw new IllegalArgumentException("selectionModel must be non null");
1884         }
1885 
1886         /* Remove the forwarding ListSelectionListener from the old
1887          * selectionModel, and add it to the new one, if necessary.
1888          */
1889         if (selectionListener != null) {
1890             this.selectionModel.removeListSelectionListener(selectionListener);
1891             selectionModel.addListSelectionListener(selectionListener);
1892         }
1893 
1894         ListSelectionModel oldValue = this.selectionModel;
1895         this.selectionModel = selectionModel;
1896         firePropertyChange("selectionModel", oldValue, selectionModel);
1897     }
1898 
1899 
1900     /**
1901      * Sets the selection mode for the list. This is a cover method that sets
1902      * the selection mode directly on the selection model.
1903      * <p>
1904      * The following list describes the accepted selection modes:
1905      * <ul>
1906      * <li>{@code ListSelectionModel.SINGLE_SELECTION} -
1907      *   Only one list index can be selected at a time. In this mode,
1908      *   {@code setSelectionInterval} and {@code addSelectionInterval} are
1909      *   equivalent, both replacing the current selection with the index
1910      *   represented by the second argument (the "lead").
1911      * <li>{@code ListSelectionModel.SINGLE_INTERVAL_SELECTION} -
1912      *   Only one contiguous interval can be selected at a time.
1913      *   In this mode, {@code addSelectionInterval} behaves like
1914      *   {@code setSelectionInterval} (replacing the current selection},
1915      *   unless the given interval is immediately adjacent to or overlaps
1916      *   the existing selection, and can be used to grow the selection.
1917      * <li>{@code ListSelectionModel.MULTIPLE_INTERVAL_SELECTION} -
1918      *   In this mode, there's no restriction on what can be selected.
1919      *   This mode is the default.
1920      * </ul>
1921      *
1922      * @param selectionMode the selection mode
1923      * @see #getSelectionMode
1924      * @throws IllegalArgumentException if the selection mode isn't
1925      *         one of those allowed
1926      */
1927     @BeanProperty(bound = false, enumerationValues = {
1928             "ListSelectionModel.SINGLE_SELECTION",
1929             "ListSelectionModel.SINGLE_INTERVAL_SELECTION",
1930             "ListSelectionModel.MULTIPLE_INTERVAL_SELECTION"}, description
1931             = "The selection mode.")
1932     public void setSelectionMode(int selectionMode) {
1933         getSelectionModel().setSelectionMode(selectionMode);
1934     }
1935 
1936     /**
1937      * Returns the current selection mode for the list. This is a cover
1938      * method that delegates to the method of the same name on the
1939      * list's selection model.
1940      *
1941      * @return the current selection mode
1942      * @see #setSelectionMode
1943      */
1944     public int getSelectionMode() {
1945         return getSelectionModel().getSelectionMode();
1946     }
1947 
1948 
1949     /**
1950      * Returns the anchor selection index. This is a cover method that
1951      * delegates to the method of the same name on the list's selection model.
1952      *
1953      * @return the anchor selection index
1954      * @see ListSelectionModel#getAnchorSelectionIndex
1955      */
1956     @BeanProperty(bound = false)
1957     public int getAnchorSelectionIndex() {
1958         return getSelectionModel().getAnchorSelectionIndex();
1959     }
1960 
1961 
1962     /**
1963      * Returns the lead selection index. This is a cover method that
1964      * delegates to the method of the same name on the list's selection model.
1965      *
1966      * @return the lead selection index
1967      * @see ListSelectionModel#getLeadSelectionIndex
1968      */
1969     @BeanProperty(bound = false, description
1970             = "The lead selection index.")
1971     public int getLeadSelectionIndex() {
1972         return getSelectionModel().getLeadSelectionIndex();
1973     }
1974 
1975 
1976     /**
1977      * Returns the smallest selected cell index, or {@code -1} if the selection
1978      * is empty. This is a cover method that delegates to the method of the same
1979      * name on the list's selection model.
1980      *
1981      * @return the smallest selected cell index, or {@code -1}
1982      * @see ListSelectionModel#getMinSelectionIndex
1983      */
1984     @BeanProperty(bound = false)
1985     public int getMinSelectionIndex() {
1986         return getSelectionModel().getMinSelectionIndex();
1987     }
1988 
1989 
1990     /**
1991      * Returns the largest selected cell index, or {@code -1} if the selection
1992      * is empty. This is a cover method that delegates to the method of the same
1993      * name on the list's selection model.
1994      *
1995      * @return the largest selected cell index
1996      * @see ListSelectionModel#getMaxSelectionIndex
1997      */
1998     @BeanProperty(bound = false)
1999     public int getMaxSelectionIndex() {
2000         return getSelectionModel().getMaxSelectionIndex();
2001     }
2002 
2003 
2004     /**
2005      * Returns {@code true} if the specified index is selected,
2006      * else {@code false}. This is a cover method that delegates to the method
2007      * of the same name on the list's selection model.
2008      *
2009      * @param index index to be queried for selection state
2010      * @return {@code true} if the specified index is selected,
2011      *         else {@code false}
2012      * @see ListSelectionModel#isSelectedIndex
2013      * @see #setSelectedIndex
2014      */
2015     public boolean isSelectedIndex(int index) {
2016         return getSelectionModel().isSelectedIndex(index);
2017     }
2018 
2019 
2020     /**
2021      * Returns {@code true} if nothing is selected, else {@code false}.
2022      * This is a cover method that delegates to the method of the same
2023      * name on the list's selection model.
2024      *
2025      * @return {@code true} if nothing is selected, else {@code false}
2026      * @see ListSelectionModel#isSelectionEmpty
2027      * @see #clearSelection
2028      */
2029     @BeanProperty(bound = false)
2030     public boolean isSelectionEmpty() {
2031         return getSelectionModel().isSelectionEmpty();
2032     }
2033 
2034 
2035     /**
2036      * Clears the selection; after calling this method, {@code isSelectionEmpty}
2037      * will return {@code true}. This is a cover method that delegates to the
2038      * method of the same name on the list's selection model.
2039      *
2040      * @see ListSelectionModel#clearSelection
2041      * @see #isSelectionEmpty
2042      */
2043     public void clearSelection() {
2044         getSelectionModel().clearSelection();
2045     }
2046 
2047 
2048     /**
2049      * Selects the specified interval. Both {@code anchor} and {@code lead}
2050      * indices are included. {@code anchor} doesn't have to be less than or
2051      * equal to {@code lead}. This is a cover method that delegates to the
2052      * method of the same name on the list's selection model.
2053      * <p>
2054      * Refer to the documentation of the selection model class being used
2055      * for details on how values less than {@code 0} are handled.
2056      *
2057      * @param anchor the first index to select
2058      * @param lead the last index to select
2059      * @see ListSelectionModel#setSelectionInterval
2060      * @see DefaultListSelectionModel#setSelectionInterval
2061      * @see #createSelectionModel
2062      * @see #addSelectionInterval
2063      * @see #removeSelectionInterval
2064      */
2065     public void setSelectionInterval(int anchor, int lead) {
2066         getSelectionModel().setSelectionInterval(anchor, lead);
2067     }
2068 
2069 
2070     /**
2071      * Sets the selection to be the union of the specified interval with current
2072      * selection. Both the {@code anchor} and {@code lead} indices are
2073      * included. {@code anchor} doesn't have to be less than or
2074      * equal to {@code lead}. This is a cover method that delegates to the
2075      * method of the same name on the list's selection model.
2076      * <p>
2077      * Refer to the documentation of the selection model class being used
2078      * for details on how values less than {@code 0} are handled.
2079      *
2080      * @param anchor the first index to add to the selection
2081      * @param lead the last index to add to the selection
2082      * @see ListSelectionModel#addSelectionInterval
2083      * @see DefaultListSelectionModel#addSelectionInterval
2084      * @see #createSelectionModel
2085      * @see #setSelectionInterval
2086      * @see #removeSelectionInterval
2087      */
2088     public void addSelectionInterval(int anchor, int lead) {
2089         getSelectionModel().addSelectionInterval(anchor, lead);
2090     }
2091 
2092 
2093     /**
2094      * Sets the selection to be the set difference of the specified interval
2095      * and the current selection. Both the {@code index0} and {@code index1}
2096      * indices are removed. {@code index0} doesn't have to be less than or
2097      * equal to {@code index1}. This is a cover method that delegates to the
2098      * method of the same name on the list's selection model.
2099      * <p>
2100      * Refer to the documentation of the selection model class being used
2101      * for details on how values less than {@code 0} are handled.
2102      *
2103      * @param index0 the first index to remove from the selection
2104      * @param index1 the last index to remove from the selection
2105      * @see ListSelectionModel#removeSelectionInterval
2106      * @see DefaultListSelectionModel#removeSelectionInterval
2107      * @see #createSelectionModel
2108      * @see #setSelectionInterval
2109      * @see #addSelectionInterval
2110      */
2111     public void removeSelectionInterval(int index0, int index1) {
2112         getSelectionModel().removeSelectionInterval(index0, index1);
2113     }
2114 
2115 
2116     /**
2117      * Sets the selection model's {@code valueIsAdjusting} property. When
2118      * {@code true}, upcoming changes to selection should be considered part
2119      * of a single change. This property is used internally and developers
2120      * typically need not call this method. For example, when the model is being
2121      * updated in response to a user drag, the value of the property is set
2122      * to {@code true} when the drag is initiated and set to {@code false}
2123      * when the drag is finished. This allows listeners to update only
2124      * when a change has been finalized, rather than handling all of the
2125      * intermediate values.
2126      * <p>
2127      * You may want to use this directly if making a series of changes
2128      * that should be considered part of a single change.
2129      * <p>
2130      * This is a cover method that delegates to the method of the same name on
2131      * the list's selection model. See the documentation for
2132      * {@link javax.swing.ListSelectionModel#setValueIsAdjusting} for
2133      * more details.
2134      *
2135      * @param b the new value for the property
2136      * @see ListSelectionModel#setValueIsAdjusting
2137      * @see javax.swing.event.ListSelectionEvent#getValueIsAdjusting
2138      * @see #getValueIsAdjusting
2139      */
2140     public void setValueIsAdjusting(boolean b) {
2141         getSelectionModel().setValueIsAdjusting(b);
2142     }
2143 
2144 
2145     /**
2146      * Returns the value of the selection model's {@code isAdjusting} property.
2147      * <p>
2148      * This is a cover method that delegates to the method of the same name on
2149      * the list's selection model.
2150      *
2151      * @return the value of the selection model's {@code isAdjusting} property.
2152      *
2153      * @see #setValueIsAdjusting
2154      * @see ListSelectionModel#getValueIsAdjusting
2155      */
2156     public boolean getValueIsAdjusting() {
2157         return getSelectionModel().getValueIsAdjusting();
2158     }
2159 
2160 
2161     /**
2162      * Returns an array of all of the selected indices, in increasing
2163      * order.
2164      *
2165      * @return all of the selected indices, in increasing order,
2166      *         or an empty array if nothing is selected
2167      * @see #removeSelectionInterval
2168      * @see #addListSelectionListener
2169      */
2170     @Transient
2171     public int[] getSelectedIndices() {
2172         ListSelectionModel sm = getSelectionModel();
2173         int iMin = sm.getMinSelectionIndex();
2174         int iMax = sm.getMaxSelectionIndex();
2175 
2176         if ((iMin < 0) || (iMax < 0)) {
2177             return new int[0];
2178         }
2179 
2180         int[] rvTmp = new int[1+ (iMax - iMin)];
2181         int n = 0;
2182         for(int i = iMin; i <= iMax; i++) {
2183             if (sm.isSelectedIndex(i)) {
2184                 rvTmp[n++] = i;
2185             }
2186         }
2187         int[] rv = new int[n];
2188         System.arraycopy(rvTmp, 0, rv, 0, n);
2189         return rv;
2190     }
2191 
2192 
2193     /**
2194      * Selects a single cell. Does nothing if the given index is greater
2195      * than or equal to the model size. This is a convenience method that uses
2196      * {@code setSelectionInterval} on the selection model. Refer to the
2197      * documentation for the selection model class being used for details on
2198      * how values less than {@code 0} are handled.
2199      *
2200      * @param index the index of the cell to select
2201      * @see ListSelectionModel#setSelectionInterval
2202      * @see #isSelectedIndex
2203      * @see #addListSelectionListener
2204      */
2205     @BeanProperty(bound = false, description
2206             = "The index of the selected cell.")
2207     public void setSelectedIndex(int index) {
2208         if (index >= getModel().getSize()) {
2209             return;
2210         }
2211         getSelectionModel().setSelectionInterval(index, index);
2212     }
2213 
2214 
2215     /**
2216      * Changes the selection to be the set of indices specified by the given
2217      * array. Indices greater than or equal to the model size are ignored.
2218      * This is a convenience method that clears the selection and then uses
2219      * {@code addSelectionInterval} on the selection model to add the indices.
2220      * Refer to the documentation of the selection model class being used for
2221      * details on how values less than {@code 0} are handled.
2222      *
2223      * @param indices an array of the indices of the cells to select,
2224      *                {@code non-null}
2225      * @see ListSelectionModel#addSelectionInterval
2226      * @see #isSelectedIndex
2227      * @see #addListSelectionListener
2228      * @throws NullPointerException if the given array is {@code null}
2229      */
2230     public void setSelectedIndices(int[] indices) {
2231         ListSelectionModel sm = getSelectionModel();
2232         sm.clearSelection();
2233         int size = getModel().getSize();
2234         for (int i : indices) {
2235             if (i < size) {
2236                 sm.addSelectionInterval(i, i);
2237             }
2238         }
2239     }
2240 
2241 
2242     /**
2243      * Returns an array of all the selected values, in increasing order based
2244      * on their indices in the list.
2245      *
2246      * @return the selected values, or an empty array if nothing is selected
2247      * @see #isSelectedIndex
2248      * @see #getModel
2249      * @see #addListSelectionListener
2250      *
2251      * @deprecated As of JDK 1.7, replaced by {@link #getSelectedValuesList()}
2252      */
2253     @Deprecated
2254     @BeanProperty(bound = false)
2255     public Object[] getSelectedValues() {
2256         ListSelectionModel sm = getSelectionModel();
2257         ListModel<E> dm = getModel();
2258 
2259         int iMin = sm.getMinSelectionIndex();
2260         int iMax = sm.getMaxSelectionIndex();
2261 
2262         if ((iMin < 0) || (iMax < 0)) {
2263             return new Object[0];
2264         }
2265 
2266         Object[] rvTmp = new Object[1+ (iMax - iMin)];
2267         int n = 0;
2268         for(int i = iMin; i <= iMax; i++) {
2269             if (sm.isSelectedIndex(i)) {
2270                 rvTmp[n++] = dm.getElementAt(i);
2271             }
2272         }
2273         Object[] rv = new Object[n];
2274         System.arraycopy(rvTmp, 0, rv, 0, n);
2275         return rv;
2276     }
2277 
2278     /**
2279      * Returns a list of all the selected items, in increasing order based
2280      * on their indices in the list.
2281      *
2282      * @return the selected items, or an empty list if nothing is selected
2283      * @see #isSelectedIndex
2284      * @see #getModel
2285      * @see #addListSelectionListener
2286      *
2287      * @since 1.7
2288      */
2289     @BeanProperty(bound = false)
2290     public List<E> getSelectedValuesList() {
2291         ListSelectionModel sm = getSelectionModel();
2292         ListModel<E> dm = getModel();
2293 
2294         int iMin = sm.getMinSelectionIndex();
2295         int iMax = sm.getMaxSelectionIndex();
2296 
2297         if ((iMin < 0) || (iMax < 0)) {
2298             return Collections.emptyList();
2299         }
2300 
2301         List<E> selectedItems = new ArrayList<E>();
2302         for(int i = iMin; i <= iMax; i++) {
2303             if (sm.isSelectedIndex(i)) {
2304                 selectedItems.add(dm.getElementAt(i));
2305             }
2306         }
2307         return selectedItems;
2308     }
2309 
2310 
2311     /**
2312      * Returns the smallest selected cell index; <i>the selection</i> when only
2313      * a single item is selected in the list. When multiple items are selected,
2314      * it is simply the smallest selected index. Returns {@code -1} if there is
2315      * no selection.
2316      * <p>
2317      * This method is a cover that delegates to {@code getMinSelectionIndex}.
2318      *
2319      * @return the smallest selected cell index
2320      * @see #getMinSelectionIndex
2321      * @see #addListSelectionListener
2322      */
2323     public int getSelectedIndex() {
2324         return getMinSelectionIndex();
2325     }
2326 
2327 
2328     /**
2329      * Returns the value for the smallest selected cell index;
2330      * <i>the selected value</i> when only a single item is selected in the
2331      * list. When multiple items are selected, it is simply the value for the
2332      * smallest selected index. Returns {@code null} if there is no selection.
2333      * <p>
2334      * This is a convenience method that simply returns the model value for
2335      * {@code getMinSelectionIndex}.
2336      *
2337      * @return the first selected value
2338      * @see #getMinSelectionIndex
2339      * @see #getModel
2340      * @see #addListSelectionListener
2341      */
2342     @BeanProperty(bound = false)
2343     public E getSelectedValue() {
2344         int i = getMinSelectionIndex();
2345         return (i == -1) ? null : getModel().getElementAt(i);
2346     }
2347 
2348 
2349     /**
2350      * Selects the specified object from the list.
2351      *
2352      * @param anObject      the object to select
2353      * @param shouldScroll  {@code true} if the list should scroll to display
2354      *                      the selected object, if one exists; otherwise {@code false}
2355      */
2356     public void setSelectedValue(Object anObject,boolean shouldScroll) {
2357         if(anObject == null)
2358             setSelectedIndex(-1);
2359         else if(!anObject.equals(getSelectedValue())) {
2360             int i,c;
2361             ListModel<E> dm = getModel();
2362             for(i=0,c=dm.getSize();i<c;i++)
2363                 if(anObject.equals(dm.getElementAt(i))){
2364                     setSelectedIndex(i);
2365                     if(shouldScroll)
2366                         ensureIndexIsVisible(i);
2367                     repaint();  /** FIX-ME setSelectedIndex does not redraw all the time with the basic l&f**/
2368                     return;
2369                 }
2370             setSelectedIndex(-1);
2371         }
2372         repaint(); /** FIX-ME setSelectedIndex does not redraw all the time with the basic l&f**/
2373     }
2374 
2375 
2376 
2377     /**
2378      * --- The Scrollable Implementation ---
2379      */
2380 
2381     private void checkScrollableParameters(Rectangle visibleRect, int orientation) {
2382         if (visibleRect == null) {
2383             throw new IllegalArgumentException("visibleRect must be non-null");
2384         }
2385         switch (orientation) {
2386         case SwingConstants.VERTICAL:
2387         case SwingConstants.HORIZONTAL:
2388             break;
2389         default:
2390             throw new IllegalArgumentException("orientation must be one of: VERTICAL, HORIZONTAL");
2391         }
2392     }
2393 
2394 
2395     /**
2396      * Computes the size of viewport needed to display {@code visibleRowCount}
2397      * rows. The value returned by this method depends on the layout
2398      * orientation:
2399      * <p>
2400      * <b>{@code VERTICAL}:</b>
2401      * <br>
2402      * This is trivial if both {@code fixedCellWidth} and {@code fixedCellHeight}
2403      * have been set (either explicitly or by specifying a prototype cell value).
2404      * The width is simply the {@code fixedCellWidth} plus the list's horizontal
2405      * insets. The height is the {@code fixedCellHeight} multiplied by the
2406      * {@code visibleRowCount}, plus the list's vertical insets.
2407      * <p>
2408      * If either {@code fixedCellWidth} or {@code fixedCellHeight} haven't been
2409      * specified, heuristics are used. If the model is empty, the width is
2410      * the {@code fixedCellWidth}, if greater than {@code 0}, or a hard-coded
2411      * value of {@code 256}. The height is the {@code fixedCellHeight} multiplied
2412      * by {@code visibleRowCount}, if {@code fixedCellHeight} is greater than
2413      * {@code 0}, otherwise it is a hard-coded value of {@code 16} multiplied by
2414      * {@code visibleRowCount}.
2415      * <p>
2416      * If the model isn't empty, the width is the preferred size's width,
2417      * typically the width of the widest list element. The height is the
2418      * {@code fixedCellHeight} multiplied by the {@code visibleRowCount},
2419      * plus the list's vertical insets.
2420      * <p>
2421      * <b>{@code VERTICAL_WRAP} or {@code HORIZONTAL_WRAP}:</b>
2422      * <br>
2423      * This method simply returns the value from {@code getPreferredSize}.
2424      * The list's {@code ListUI} is expected to override {@code getPreferredSize}
2425      * to return an appropriate value.
2426      *
2427      * @return a dimension containing the size of the viewport needed
2428      *          to display {@code visibleRowCount} rows
2429      * @see #getPreferredScrollableViewportSize
2430      * @see #setPrototypeCellValue
2431      */
2432     @BeanProperty(bound = false)
2433     public Dimension getPreferredScrollableViewportSize()
2434     {
2435         if (getLayoutOrientation() != VERTICAL) {
2436             return getPreferredSize();
2437         }
2438         Insets insets = getInsets();
2439         int dx = insets.left + insets.right;
2440         int dy = insets.top + insets.bottom;
2441 
2442         int visibleRowCount = getVisibleRowCount();
2443         int fixedCellWidth = getFixedCellWidth();
2444         int fixedCellHeight = getFixedCellHeight();
2445 
2446         if ((fixedCellWidth > 0) && (fixedCellHeight > 0)) {
2447             int width = fixedCellWidth + dx;
2448             int height = (visibleRowCount * fixedCellHeight) + dy;
2449             return new Dimension(width, height);
2450         }
2451         else if (getModel().getSize() > 0) {
2452             int width = getPreferredSize().width;
2453             int height;
2454             Rectangle r = getCellBounds(0, 0);
2455             if (r != null) {
2456                 height = (visibleRowCount * r.height) + dy;
2457             }
2458             else {
2459                 // Will only happen if UI null, shouldn't matter what we return
2460                 height = 1;
2461             }
2462             return new Dimension(width, height);
2463         }
2464         else {
2465             fixedCellWidth = (fixedCellWidth > 0) ? fixedCellWidth : 256;
2466             fixedCellHeight = (fixedCellHeight > 0) ? fixedCellHeight : 16;
2467             return new Dimension(fixedCellWidth, fixedCellHeight * visibleRowCount);
2468         }
2469     }
2470 
2471 
2472     /**
2473      * Returns the distance to scroll to expose the next or previous
2474      * row (for vertical scrolling) or column (for horizontal scrolling).
2475      * <p>
2476      * For horizontal scrolling, if the layout orientation is {@code VERTICAL},
2477      * then the list's font size is returned (or {@code 1} if the font is
2478      * {@code null}).
2479      *
2480      * @param visibleRect the view area visible within the viewport
2481      * @param orientation {@code SwingConstants.HORIZONTAL} or
2482      *                    {@code SwingConstants.VERTICAL}
2483      * @param direction less or equal to zero to scroll up/back,
2484      *                  greater than zero for down/forward
2485      * @return the "unit" increment for scrolling in the specified direction;
2486      *         always positive
2487      * @see #getScrollableBlockIncrement
2488      * @see Scrollable#getScrollableUnitIncrement
2489      * @throws IllegalArgumentException if {@code visibleRect} is {@code null}, or
2490      *         {@code orientation} isn't one of {@code SwingConstants.VERTICAL} or
2491      *         {@code SwingConstants.HORIZONTAL}
2492      */
2493     public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
2494     {
2495         checkScrollableParameters(visibleRect, orientation);
2496 
2497         if (orientation == SwingConstants.VERTICAL) {
2498             int row = locationToIndex(visibleRect.getLocation());
2499 
2500             if (row == -1) {
2501                 return 0;
2502             }
2503             else {
2504                 /* Scroll Down */
2505                 if (direction > 0) {
2506                     Rectangle r = getCellBounds(row, row);
2507                     return (r == null) ? 0 : r.height - (visibleRect.y - r.y);
2508                 }
2509                 /* Scroll Up */
2510                 else {
2511                     Rectangle r = getCellBounds(row, row);
2512 
2513                     /* The first row is completely visible and it's row 0.
2514                      * We're done.
2515                      */
2516                     if ((r.y == visibleRect.y) && (row == 0))  {
2517                         return 0;
2518                     }
2519                     /* The first row is completely visible, return the
2520                      * height of the previous row or 0 if the first row
2521                      * is the top row of the list.
2522                      */
2523                     else if (r.y == visibleRect.y) {
2524                         Point loc = r.getLocation();
2525                         loc.y--;
2526                         int prevIndex = locationToIndex(loc);
2527                         Rectangle prevR = getCellBounds(prevIndex, prevIndex);
2528 
2529                         if (prevR == null || prevR.y >= r.y) {
2530                             return 0;
2531                         }
2532                         return prevR.height;
2533                     }
2534                     /* The first row is partially visible, return the
2535                      * height of hidden part.
2536                      */
2537                     else {
2538                         return visibleRect.y - r.y;
2539                     }
2540                 }
2541             }
2542         } else if (orientation == SwingConstants.HORIZONTAL &&
2543                            getLayoutOrientation() != JList.VERTICAL) {
2544             boolean leftToRight = getComponentOrientation().isLeftToRight();
2545             int index;
2546             Point leadingPoint;
2547 
2548             if (leftToRight) {
2549                 leadingPoint = visibleRect.getLocation();
2550             }
2551             else {
2552                 leadingPoint = new Point(visibleRect.x + visibleRect.width -1,
2553                                          visibleRect.y);
2554             }
2555             index = locationToIndex(leadingPoint);
2556 
2557             if (index != -1) {
2558                 Rectangle cellBounds = getCellBounds(index, index);
2559                 if (cellBounds != null && cellBounds.contains(leadingPoint)) {
2560                     int leadingVisibleEdge;
2561                     int leadingCellEdge;
2562 
2563                     if (leftToRight) {
2564                         leadingVisibleEdge = visibleRect.x;
2565                         leadingCellEdge = cellBounds.x;
2566                     }
2567                     else {
2568                         leadingVisibleEdge = visibleRect.x + visibleRect.width;
2569                         leadingCellEdge = cellBounds.x + cellBounds.width;
2570                     }
2571 
2572                     if (leadingCellEdge != leadingVisibleEdge) {
2573                         if (direction < 0) {
2574                             // Show remainder of leading cell
2575                             return Math.abs(leadingVisibleEdge - leadingCellEdge);
2576 
2577                         }
2578                         else if (leftToRight) {
2579                             // Hide rest of leading cell
2580                             return leadingCellEdge + cellBounds.width - leadingVisibleEdge;
2581                         }
2582                         else {
2583                             // Hide rest of leading cell
2584                             return leadingVisibleEdge - cellBounds.x;
2585                         }
2586                     }
2587                     // ASSUME: All cells are the same width
2588                     return cellBounds.width;
2589                 }
2590             }
2591         }
2592         Font f = getFont();
2593         return (f != null) ? f.getSize() : 1;
2594     }
2595 
2596 
2597     /**
2598      * Returns the distance to scroll to expose the next or previous block.
2599      * <p>
2600      * For vertical scrolling, the following rules are used:
2601      * <ul>
2602      * <li>if scrolling down, returns the distance to scroll so that the last
2603      * visible element becomes the first completely visible element
2604      * <li>if scrolling up, returns the distance to scroll so that the first
2605      * visible element becomes the last completely visible element
2606      * <li>returns {@code visibleRect.height} if the list is empty
2607      * </ul>
2608      * <p>
2609      * For horizontal scrolling, when the layout orientation is either
2610      * {@code VERTICAL_WRAP} or {@code HORIZONTAL_WRAP}:
2611      * <ul>
2612      * <li>if scrolling right, returns the distance to scroll so that the
2613      * last visible element becomes
2614      * the first completely visible element
2615      * <li>if scrolling left, returns the distance to scroll so that the first
2616      * visible element becomes the last completely visible element
2617      * <li>returns {@code visibleRect.width} if the list is empty
2618      * </ul>
2619      * <p>
2620      * For horizontal scrolling and {@code VERTICAL} orientation,
2621      * returns {@code visibleRect.width}.
2622      * <p>
2623      * Note that the value of {@code visibleRect} must be the equal to
2624      * {@code this.getVisibleRect()}.
2625      *
2626      * @param visibleRect the view area visible within the viewport
2627      * @param orientation {@code SwingConstants.HORIZONTAL} or
2628      *                    {@code SwingConstants.VERTICAL}
2629      * @param direction less or equal to zero to scroll up/back,
2630      *                  greater than zero for down/forward
2631      * @return the "block" increment for scrolling in the specified direction;
2632      *         always positive
2633      * @see #getScrollableUnitIncrement
2634      * @see Scrollable#getScrollableBlockIncrement
2635      * @throws IllegalArgumentException if {@code visibleRect} is {@code null}, or
2636      *         {@code orientation} isn't one of {@code SwingConstants.VERTICAL} or
2637      *         {@code SwingConstants.HORIZONTAL}
2638      */
2639     public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
2640         checkScrollableParameters(visibleRect, orientation);
2641         if (orientation == SwingConstants.VERTICAL) {
2642             int inc = visibleRect.height;
2643             /* Scroll Down */
2644             if (direction > 0) {
2645                 // last cell is the lowest left cell
2646                 int last = locationToIndex(new Point(visibleRect.x, visibleRect.y+visibleRect.height-1));
2647                 if (last != -1) {
2648                     Rectangle lastRect = getCellBounds(last,last);
2649                     if (lastRect != null) {
2650                         inc = lastRect.y - visibleRect.y;
2651                         if ( (inc == 0) && (last < getModel().getSize()-1) ) {
2652                             inc = lastRect.height;
2653                         }
2654                     }
2655                 }
2656             }
2657             /* Scroll Up */
2658             else {
2659                 int newFirst = locationToIndex(new Point(visibleRect.x, visibleRect.y-visibleRect.height));
2660                 int first = getFirstVisibleIndex();
2661                 if (newFirst != -1) {
2662                     if (first == -1) {
2663                         first = locationToIndex(visibleRect.getLocation());
2664                     }
2665                     Rectangle newFirstRect = getCellBounds(newFirst,newFirst);
2666                     Rectangle firstRect = getCellBounds(first,first);
2667                     if ((newFirstRect != null) && (firstRect!=null)) {
2668                         while ( (newFirstRect.y + visibleRect.height <
2669                                  firstRect.y + firstRect.height) &&
2670                                 (newFirstRect.y < firstRect.y) ) {
2671                             newFirst++;
2672                             newFirstRect = getCellBounds(newFirst,newFirst);
2673                         }
2674                         inc = visibleRect.y - newFirstRect.y;
2675                         if ( (inc <= 0) && (newFirstRect.y > 0)) {
2676                             newFirst--;
2677                             newFirstRect = getCellBounds(newFirst,newFirst);
2678                             if (newFirstRect != null) {
2679                                 inc = visibleRect.y - newFirstRect.y;
2680                             }
2681                         }
2682                     }
2683                 }
2684             }
2685             return inc;
2686         }
2687         else if (orientation == SwingConstants.HORIZONTAL &&
2688                  getLayoutOrientation() != JList.VERTICAL) {
2689             boolean leftToRight = getComponentOrientation().isLeftToRight();
2690             int inc = visibleRect.width;
2691             /* Scroll Right (in ltr mode) or Scroll Left (in rtl mode) */
2692             if (direction > 0) {
2693                 // position is upper right if ltr, or upper left otherwise
2694                 int x = visibleRect.x + (leftToRight ? (visibleRect.width - 1) : 0);
2695                 int last = locationToIndex(new Point(x, visibleRect.y));
2696 
2697                 if (last != -1) {
2698                     Rectangle lastRect = getCellBounds(last,last);
2699                     if (lastRect != null) {
2700                         if (leftToRight) {
2701                             inc = lastRect.x - visibleRect.x;
2702                         } else {
2703                             inc = visibleRect.x + visibleRect.width
2704                                       - (lastRect.x + lastRect.width);
2705                         }
2706                         if (inc < 0) {
2707                             inc += lastRect.width;
2708                         } else if ( (inc == 0) && (last < getModel().getSize()-1) ) {
2709                             inc = lastRect.width;
2710                         }
2711                     }
2712                 }
2713             }
2714             /* Scroll Left (in ltr mode) or Scroll Right (in rtl mode) */
2715             else {
2716                 // position is upper left corner of the visibleRect shifted
2717                 // left by the visibleRect.width if ltr, or upper right shifted
2718                 // right by the visibleRect.width otherwise
2719                 int x = visibleRect.x + (leftToRight
2720                                          ? -visibleRect.width
2721                                          : visibleRect.width - 1 + visibleRect.width);
2722                 int first = locationToIndex(new Point(x, visibleRect.y));
2723 
2724                 if (first != -1) {
2725                     Rectangle firstRect = getCellBounds(first,first);
2726                     if (firstRect != null) {
2727                         // the right of the first cell
2728                         int firstRight = firstRect.x + firstRect.width;
2729 
2730                         if (leftToRight) {
2731                             if ((firstRect.x < visibleRect.x - visibleRect.width)
2732                                     && (firstRight < visibleRect.x)) {
2733                                 inc = visibleRect.x - firstRight;
2734                             } else {
2735                                 inc = visibleRect.x - firstRect.x;
2736                             }
2737                         } else {
2738                             int visibleRight = visibleRect.x + visibleRect.width;
2739 
2740                             if ((firstRight > visibleRight + visibleRect.width)
2741                                     && (firstRect.x > visibleRight)) {
2742                                 inc = firstRect.x - visibleRight;
2743                             } else {
2744                                 inc = firstRight - visibleRight;
2745                             }
2746                         }
2747                     }
2748                 }
2749             }
2750             return inc;
2751         }
2752         return visibleRect.width;
2753     }
2754 
2755 
2756     /**
2757      * Returns {@code true} if this {@code JList} is displayed in a
2758      * {@code JViewport} and the viewport is wider than the list's
2759      * preferred width, or if the layout orientation is {@code HORIZONTAL_WRAP}
2760      * and {@code visibleRowCount <= 0}; otherwise returns {@code false}.
2761      * <p>
2762      * If {@code false}, then don't track the viewport's width. This allows
2763      * horizontal scrolling if the {@code JViewport} is itself embedded in a
2764      * {@code JScrollPane}.
2765      *
2766      * @return whether or not an enclosing viewport should force the list's
2767      *         width to match its own
2768      * @see Scrollable#getScrollableTracksViewportWidth
2769      */
2770     @BeanProperty(bound = false)
2771     public boolean getScrollableTracksViewportWidth() {
2772         if (getLayoutOrientation() == HORIZONTAL_WRAP &&
2773                                       getVisibleRowCount() <= 0) {
2774             return true;
2775         }
2776         Container parent = SwingUtilities.getUnwrappedParent(this);
2777         if (parent instanceof JViewport) {
2778             return parent.getWidth() > getPreferredSize().width;
2779         }
2780         return false;
2781     }
2782 
2783     /**
2784      * Returns {@code true} if this {@code JList} is displayed in a
2785      * {@code JViewport} and the viewport is taller than the list's
2786      * preferred height, or if the layout orientation is {@code VERTICAL_WRAP}
2787      * and {@code visibleRowCount <= 0}; otherwise returns {@code false}.
2788      * <p>
2789      * If {@code false}, then don't track the viewport's height. This allows
2790      * vertical scrolling if the {@code JViewport} is itself embedded in a
2791      * {@code JScrollPane}.
2792      *
2793      * @return whether or not an enclosing viewport should force the list's
2794      *         height to match its own
2795      * @see Scrollable#getScrollableTracksViewportHeight
2796      */
2797     @BeanProperty(bound = false)
2798     public boolean getScrollableTracksViewportHeight() {
2799         if (getLayoutOrientation() == VERTICAL_WRAP &&
2800                      getVisibleRowCount() <= 0) {
2801             return true;
2802         }
2803         Container parent = SwingUtilities.getUnwrappedParent(this);
2804         if (parent instanceof JViewport) {
2805             return parent.getHeight() > getPreferredSize().height;
2806         }
2807         return false;
2808     }
2809 
2810 
2811     /*
2812      * See {@code readObject} and {@code writeObject} in {@code JComponent}
2813      * for more information about serialization in Swing.
2814      */
2815     private void writeObject(ObjectOutputStream s) throws IOException {
2816         s.defaultWriteObject();
2817         if (getUIClassID().equals(uiClassID)) {
2818             byte count = JComponent.getWriteObjCounter(this);
2819             JComponent.setWriteObjCounter(this, --count);
2820             if (count == 0 && ui != null) {
2821                 ui.installUI(this);
2822             }
2823         }
2824     }
2825 
2826 
2827     /**
2828      * Returns a {@code String} representation of this {@code JList}.
2829      * This method is intended to be used only for debugging purposes,
2830      * and the content and format of the returned {@code String} may vary
2831      * between implementations. The returned {@code String} may be empty,
2832      * but may not be {@code null}.
2833      *
2834      * @return  a {@code String} representation of this {@code JList}.
2835      */
2836     protected String paramString() {
2837         String selectionForegroundString = (selectionForeground != null ?
2838                                             selectionForeground.toString() :
2839                                             "");
2840         String selectionBackgroundString = (selectionBackground != null ?
2841                                             selectionBackground.toString() :
2842                                             "");
2843 
2844         return super.paramString() +
2845         ",fixedCellHeight=" + fixedCellHeight +
2846         ",fixedCellWidth=" + fixedCellWidth +
2847         ",horizontalScrollIncrement=" + horizontalScrollIncrement +
2848         ",selectionBackground=" + selectionBackgroundString +
2849         ",selectionForeground=" + selectionForegroundString +
2850         ",visibleRowCount=" + visibleRowCount +
2851         ",layoutOrientation=" + layoutOrientation;
2852     }
2853 
2854 
2855     /**
2856      * --- Accessibility Support ---
2857      */
2858 
2859     /**
2860      * Gets the {@code AccessibleContext} associated with this {@code JList}.
2861      * For {@code JList}, the {@code AccessibleContext} takes the form of an
2862      * {@code AccessibleJList}.
2863      * <p>
2864      * A new {@code AccessibleJList} instance is created if necessary.
2865      *
2866      * @return an {@code AccessibleJList} that serves as the
2867      *         {@code AccessibleContext} of this {@code JList}
2868      */
2869     @BeanProperty(bound = false)
2870     public AccessibleContext getAccessibleContext() {
2871         if (accessibleContext == null) {
2872             accessibleContext = new AccessibleJList();
2873         }
2874         return accessibleContext;
2875     }
2876 
2877     /**
2878      * This class implements accessibility support for the
2879      * {@code JList} class. It provides an implementation of the
2880      * Java Accessibility API appropriate to list user-interface
2881      * elements.
2882      * <p>
2883      * <strong>Warning:</strong>
2884      * Serialized objects of this class will not be compatible with
2885      * future Swing releases. The current serialization support is
2886      * appropriate for short term storage or RMI between applications running
2887      * the same version of Swing.  As of 1.4, support for long term storage
2888      * of all JavaBeans&trade;
2889      * has been added to the <code>java.beans</code> package.
2890      * Please see {@link java.beans.XMLEncoder}.
2891      */
2892     @SuppressWarnings("serial") // Same-version serialization only
2893     protected class AccessibleJList extends AccessibleJComponent
2894         implements AccessibleSelection, PropertyChangeListener,
2895         ListSelectionListener, ListDataListener {
2896 
2897         int leadSelectionIndex;
2898 
2899         /**
2900          * Constructs an {@code AccessibleJList}.
2901          */
2902         public AccessibleJList() {
2903             super();
2904             JList.this.addPropertyChangeListener(this);
2905             JList.this.getSelectionModel().addListSelectionListener(this);
2906             JList.this.getModel().addListDataListener(this);
2907             leadSelectionIndex = JList.this.getLeadSelectionIndex();
2908         }
2909 
2910         /**
2911          * Property Change Listener change method. Used to track changes
2912          * to the DataModel and ListSelectionModel, in order to re-set
2913          * listeners to those for reporting changes there via the Accessibility
2914          * PropertyChange mechanism.
2915          *
2916          * @param e PropertyChangeEvent
2917          */
2918         public void propertyChange(PropertyChangeEvent e) {
2919             String name = e.getPropertyName();
2920             Object oldValue = e.getOldValue();
2921             Object newValue = e.getNewValue();
2922 
2923                 // re-set listData listeners
2924             if (name.compareTo("model") == 0) {
2925 
2926                 if (oldValue != null && oldValue instanceof ListModel) {
2927                     ((ListModel) oldValue).removeListDataListener(this);
2928                 }
2929                 if (newValue != null && newValue instanceof ListModel) {
2930                     ((ListModel) newValue).addListDataListener(this);
2931                 }
2932 
2933                 // re-set listSelectionModel listeners
2934             } else if (name.compareTo("selectionModel") == 0) {
2935 
2936                 if (oldValue != null && oldValue instanceof ListSelectionModel) {
2937                     ((ListSelectionModel) oldValue).removeListSelectionListener(this);
2938                 }
2939                 if (newValue != null && newValue instanceof ListSelectionModel) {
2940                     ((ListSelectionModel) newValue).addListSelectionListener(this);
2941                 }
2942 
2943                 firePropertyChange(
2944                     AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
2945                     Boolean.valueOf(false), Boolean.valueOf(true));
2946             }
2947         }
2948 
2949         /**
2950          * List Selection Listener value change method. Used to fire
2951          * the property change
2952          *
2953          * @param e ListSelectionEvent
2954          *
2955          */
2956         public void valueChanged(ListSelectionEvent e) {
2957             int oldLeadSelectionIndex = leadSelectionIndex;
2958             leadSelectionIndex = JList.this.getLeadSelectionIndex();
2959             if (oldLeadSelectionIndex != leadSelectionIndex) {
2960                 Accessible oldLS, newLS;
2961                 oldLS = (oldLeadSelectionIndex >= 0)
2962                         ? getAccessibleChild(oldLeadSelectionIndex)
2963                         : null;
2964                 newLS = (leadSelectionIndex >= 0)
2965                         ? getAccessibleChild(leadSelectionIndex)
2966                         : null;
2967                 firePropertyChange(AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY,
2968                                    oldLS, newLS);
2969             }
2970 
2971             firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
2972                                Boolean.valueOf(false), Boolean.valueOf(true));
2973             firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
2974                                Boolean.valueOf(false), Boolean.valueOf(true));
2975 
2976             // Process the State changes for Multiselectable
2977             AccessibleStateSet s = getAccessibleStateSet();
2978             ListSelectionModel lsm = JList.this.getSelectionModel();
2979             if (lsm.getSelectionMode() != ListSelectionModel.SINGLE_SELECTION) {
2980                 if (!s.contains(AccessibleState.MULTISELECTABLE)) {
2981                     s.add(AccessibleState.MULTISELECTABLE);
2982                     firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
2983                                        null, AccessibleState.MULTISELECTABLE);
2984                 }
2985             } else {
2986                 if (s.contains(AccessibleState.MULTISELECTABLE)) {
2987                     s.remove(AccessibleState.MULTISELECTABLE);
2988                     firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
2989                                        AccessibleState.MULTISELECTABLE, null);
2990                 }
2991             }
2992         }
2993 
2994         /**
2995          * List Data Listener interval added method. Used to fire the visible data property change
2996          *
2997          * @param e ListDataEvent
2998          *
2999          */
3000         public void intervalAdded(ListDataEvent e) {
3001             firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
3002                                Boolean.valueOf(false), Boolean.valueOf(true));
3003         }
3004 
3005         /**
3006          * List Data Listener interval removed method. Used to fire the visible data property change
3007          *
3008          * @param e ListDataEvent
3009          *
3010          */
3011         public void intervalRemoved(ListDataEvent e) {
3012             firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
3013                                Boolean.valueOf(false), Boolean.valueOf(true));
3014         }
3015 
3016         /**
3017          * List Data Listener contents changed method. Used to fire the visible data property change
3018          *
3019          * @param e ListDataEvent
3020          *
3021          */
3022          public void contentsChanged(ListDataEvent e) {
3023              firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
3024                                 Boolean.valueOf(false), Boolean.valueOf(true));
3025          }
3026 
3027     // AccessibleContext methods
3028 
3029         /**
3030          * Get the state set of this object.
3031          *
3032          * @return an instance of AccessibleState containing the current state
3033          * of the object
3034          * @see AccessibleState
3035          */
3036         public AccessibleStateSet getAccessibleStateSet() {
3037             AccessibleStateSet states = super.getAccessibleStateSet();
3038             if (selectionModel.getSelectionMode() !=
3039                 ListSelectionModel.SINGLE_SELECTION) {
3040                 states.add(AccessibleState.MULTISELECTABLE);
3041             }
3042             return states;
3043         }
3044 
3045         /**
3046          * Get the role of this object.
3047          *
3048          * @return an instance of AccessibleRole describing the role of the
3049          * object
3050          * @see AccessibleRole
3051          */
3052         public AccessibleRole getAccessibleRole() {
3053             return AccessibleRole.LIST;
3054         }
3055 
3056         /**
3057          * Returns the <code>Accessible</code> child contained at
3058          * the local coordinate <code>Point</code>, if one exists.
3059          * Otherwise returns <code>null</code>.
3060          *
3061          * @return the <code>Accessible</code> at the specified
3062          *    location, if it exists
3063          */
3064         public Accessible getAccessibleAt(Point p) {
3065             int i = locationToIndex(p);
3066             if (i >= 0) {
3067                 return new AccessibleJListChild(JList.this, i);
3068             } else {
3069                 return null;
3070             }
3071         }
3072 
3073         /**
3074          * Returns the number of accessible children in the object.  If all
3075          * of the children of this object implement Accessible, than this
3076          * method should return the number of children of this object.
3077          *
3078          * @return the number of accessible children in the object.
3079          */
3080         public int getAccessibleChildrenCount() {
3081             return getModel().getSize();
3082         }
3083 
3084         /**
3085          * Return the nth Accessible child of the object.
3086          *
3087          * @param i zero-based index of child
3088          * @return the nth Accessible child of the object
3089          */
3090         public Accessible getAccessibleChild(int i) {
3091             if (i >= getModel().getSize()) {
3092                 return null;
3093             } else {
3094                 return new AccessibleJListChild(JList.this, i);
3095             }
3096         }
3097 
3098         /**
3099          * Get the AccessibleSelection associated with this object.  In the
3100          * implementation of the Java Accessibility API for this class,
3101          * return this object, which is responsible for implementing the
3102          * AccessibleSelection interface on behalf of itself.
3103          *
3104          * @return this object
3105          */
3106         public AccessibleSelection getAccessibleSelection() {
3107             return this;
3108         }
3109 
3110 
3111     // AccessibleSelection methods
3112 
3113         /**
3114          * Returns the number of items currently selected.
3115          * If no items are selected, the return value will be 0.
3116          *
3117          * @return the number of items currently selected.
3118          */
3119          public int getAccessibleSelectionCount() {
3120              return JList.this.getSelectedIndices().length;
3121          }
3122 
3123         /**
3124          * Returns an Accessible representing the specified selected item
3125          * in the object.  If there isn't a selection, or there are
3126          * fewer items selected than the integer passed in, the return
3127          * value will be <code>null</code>.
3128          *
3129          * @param i the zero-based index of selected items
3130          * @return an Accessible containing the selected item
3131          */
3132          public Accessible getAccessibleSelection(int i) {
3133              int len = getAccessibleSelectionCount();
3134              if (i < 0 || i >= len) {
3135                  return null;
3136              } else {
3137                  return getAccessibleChild(JList.this.getSelectedIndices()[i]);
3138              }
3139          }
3140 
3141         /**
3142          * Returns true if the current child of this object is selected.
3143          *
3144          * @param i the zero-based index of the child in this Accessible
3145          * object.
3146          * @see AccessibleContext#getAccessibleChild
3147          */
3148         public boolean isAccessibleChildSelected(int i) {
3149             return isSelectedIndex(i);
3150         }
3151 
3152         /**
3153          * Adds the specified selected item in the object to the object's
3154          * selection.  If the object supports multiple selections,
3155          * the specified item is added to any existing selection, otherwise
3156          * it replaces any existing selection in the object.  If the
3157          * specified item is already selected, this method has no effect.
3158          *
3159          * @param i the zero-based index of selectable items
3160          */
3161          public void addAccessibleSelection(int i) {
3162              JList.this.addSelectionInterval(i, i);
3163          }
3164 
3165         /**
3166          * Removes the specified selected item in the object from the object's
3167          * selection.  If the specified item isn't currently selected, this
3168          * method has no effect.
3169          *
3170          * @param i the zero-based index of selectable items
3171          */
3172          public void removeAccessibleSelection(int i) {
3173              JList.this.removeSelectionInterval(i, i);
3174          }
3175 
3176         /**
3177          * Clears the selection in the object, so that nothing in the
3178          * object is selected.
3179          */
3180          public void clearAccessibleSelection() {
3181              JList.this.clearSelection();
3182          }
3183 
3184         /**
3185          * Causes every selected item in the object to be selected
3186          * if the object supports multiple selections.
3187          */
3188          public void selectAllAccessibleSelection() {
3189              JList.this.addSelectionInterval(0, getAccessibleChildrenCount() -1);
3190          }
3191 
3192           /**
3193            * This class implements accessibility support appropriate
3194            * for list children.
3195            */
3196         protected class AccessibleJListChild extends AccessibleContext
3197                 implements Accessible, AccessibleComponent, AccessibleAction {
3198             private JList<E>     parent = null;
3199             int indexInParent;
3200             private Component component = null;
3201             private AccessibleContext accessibleContext = null;
3202             private ListModel<E> listModel;
3203             private ListCellRenderer<? super E> cellRenderer = null;
3204 
3205             /**
3206              * Constructs an {@code AccessibleJListChild}.
3207              * @param parent the parent
3208              * @param indexInParent the index in the parent
3209              */
3210             public AccessibleJListChild(JList<E> parent, int indexInParent) {
3211                 this.parent = parent;
3212                 this.setAccessibleParent(parent);
3213                 this.indexInParent = indexInParent;
3214                 if (parent != null) {
3215                     listModel = parent.getModel();
3216                     cellRenderer = parent.getCellRenderer();
3217                 }
3218             }
3219 
3220             private Component getCurrentComponent() {
3221                 return getComponentAtIndex(indexInParent);
3222             }
3223 
3224             AccessibleContext getCurrentAccessibleContext() {
3225                 Component c = getComponentAtIndex(indexInParent);
3226                 if (c instanceof Accessible) {
3227                     return c.getAccessibleContext();
3228                 } else {
3229                     return null;
3230                 }
3231             }
3232 
3233             private Component getComponentAtIndex(int index) {
3234                 if (index < 0 || index >= listModel.getSize()) {
3235                     return null;
3236                 }
3237                 if ((parent != null)
3238                         && (listModel != null)
3239                         && cellRenderer != null) {
3240                     E value = listModel.getElementAt(index);
3241                     boolean isSelected = parent.isSelectedIndex(index);
3242                     boolean isFocussed = parent.isFocusOwner()
3243                             && (index == parent.getLeadSelectionIndex());
3244                     return cellRenderer.getListCellRendererComponent(
3245                             parent,
3246                             value,
3247                             index,
3248                             isSelected,
3249                             isFocussed);
3250                 } else {
3251                     return null;
3252                 }
3253             }
3254 
3255 
3256             // Accessible Methods
3257            /**
3258             * Get the AccessibleContext for this object. In the
3259             * implementation of the Java Accessibility API for this class,
3260             * returns this object, which is its own AccessibleContext.
3261             *
3262             * @return this object
3263             */
3264             public AccessibleContext getAccessibleContext() {
3265                 return this;
3266             }
3267 
3268 
3269             // AccessibleContext methods
3270 
3271             public String getAccessibleName() {
3272                 AccessibleContext ac = getCurrentAccessibleContext();
3273                 if (ac != null) {
3274                     return ac.getAccessibleName();
3275                 } else {
3276                     return null;
3277                 }
3278             }
3279 
3280             public void setAccessibleName(String s) {
3281                 AccessibleContext ac = getCurrentAccessibleContext();
3282                 if (ac != null) {
3283                     ac.setAccessibleName(s);
3284                 }
3285             }
3286 
3287             public String getAccessibleDescription() {
3288                 AccessibleContext ac = getCurrentAccessibleContext();
3289                 if (ac != null) {
3290                     return ac.getAccessibleDescription();
3291                 } else {
3292                     return null;
3293                 }
3294             }
3295 
3296             public void setAccessibleDescription(String s) {
3297                 AccessibleContext ac = getCurrentAccessibleContext();
3298                 if (ac != null) {
3299                     ac.setAccessibleDescription(s);
3300                 }
3301             }
3302 
3303             public AccessibleRole getAccessibleRole() {
3304                 AccessibleContext ac = getCurrentAccessibleContext();
3305                 if (ac != null) {
3306                     return ac.getAccessibleRole();
3307                 } else {
3308                     return null;
3309                 }
3310             }
3311 
3312             public AccessibleStateSet getAccessibleStateSet() {
3313                 AccessibleContext ac = getCurrentAccessibleContext();
3314                 AccessibleStateSet s;
3315                 if (ac != null) {
3316                     s = ac.getAccessibleStateSet();
3317                 } else {
3318                     s = new AccessibleStateSet();
3319                 }
3320 
3321                 s.add(AccessibleState.SELECTABLE);
3322                 if (parent.isFocusOwner()
3323                     && (indexInParent == parent.getLeadSelectionIndex())) {
3324                     s.add(AccessibleState.ACTIVE);
3325                 }
3326                 if (parent.isSelectedIndex(indexInParent)) {
3327                     s.add(AccessibleState.SELECTED);
3328                 }
3329                 if (this.isShowing()) {
3330                     s.add(AccessibleState.SHOWING);
3331                 } else if (s.contains(AccessibleState.SHOWING)) {
3332                     s.remove(AccessibleState.SHOWING);
3333                 }
3334                 if (this.isVisible()) {
3335                     s.add(AccessibleState.VISIBLE);
3336                 } else if (s.contains(AccessibleState.VISIBLE)) {
3337                     s.remove(AccessibleState.VISIBLE);
3338                 }
3339                 s.add(AccessibleState.TRANSIENT); // cell-rendered
3340                 return s;
3341             }
3342 
3343             public int getAccessibleIndexInParent() {
3344                 return indexInParent;
3345             }
3346 
3347             public int getAccessibleChildrenCount() {
3348                 AccessibleContext ac = getCurrentAccessibleContext();
3349                 if (ac != null) {
3350                     return ac.getAccessibleChildrenCount();
3351                 } else {
3352                     return 0;
3353                 }
3354             }
3355 
3356             public Accessible getAccessibleChild(int i) {
3357                 AccessibleContext ac = getCurrentAccessibleContext();
3358                 if (ac != null) {
3359                     Accessible accessibleChild = ac.getAccessibleChild(i);
3360                     ac.setAccessibleParent(this);
3361                     return accessibleChild;
3362                 } else {
3363                     return null;
3364                 }
3365             }
3366 
3367             public Locale getLocale() {
3368                 AccessibleContext ac = getCurrentAccessibleContext();
3369                 if (ac != null) {
3370                     return ac.getLocale();
3371                 } else {
3372                     return null;
3373                 }
3374             }
3375 
3376             public void addPropertyChangeListener(PropertyChangeListener l) {
3377                 AccessibleContext ac = getCurrentAccessibleContext();
3378                 if (ac != null) {
3379                     ac.addPropertyChangeListener(l);
3380                 }
3381             }
3382 
3383             public void removePropertyChangeListener(PropertyChangeListener l) {
3384                 AccessibleContext ac = getCurrentAccessibleContext();
3385                 if (ac != null) {
3386                     ac.removePropertyChangeListener(l);
3387                 }
3388             }
3389 
3390            /**
3391             * Get the AccessibleComponent associated with this object.  In the
3392             * implementation of the Java Accessibility API for this class,
3393             * return this object, which is responsible for implementing the
3394             * AccessibleComponent interface on behalf of itself.
3395             *
3396             * @return this object
3397             */
3398             public AccessibleComponent getAccessibleComponent() {
3399                 return this; // to override getBounds()
3400             }
3401 
3402             public AccessibleSelection getAccessibleSelection() {
3403                 AccessibleContext ac = getCurrentAccessibleContext();
3404                 return ac != null ? ac.getAccessibleSelection() : null;
3405             }
3406 
3407             public AccessibleText getAccessibleText() {
3408                 AccessibleContext ac = getCurrentAccessibleContext();
3409                 return ac != null ? ac.getAccessibleText() : null;
3410             }
3411 
3412             public AccessibleValue getAccessibleValue() {
3413                 AccessibleContext ac = getCurrentAccessibleContext();
3414                 return ac != null ? ac.getAccessibleValue() : null;
3415             }
3416 
3417 
3418             // AccessibleComponent methods
3419 
3420             public Color getBackground() {
3421                 AccessibleContext ac = getCurrentAccessibleContext();
3422                 if (ac instanceof AccessibleComponent) {
3423                     return ((AccessibleComponent) ac).getBackground();
3424                 } else {
3425                     Component c = getCurrentComponent();
3426                     if (c != null) {
3427                         return c.getBackground();
3428                     } else {
3429                         return null;
3430                     }
3431                 }
3432             }
3433 
3434             public void setBackground(Color c) {
3435                 AccessibleContext ac = getCurrentAccessibleContext();
3436                 if (ac instanceof AccessibleComponent) {
3437                     ((AccessibleComponent) ac).setBackground(c);
3438                 } else {
3439                     Component cp = getCurrentComponent();
3440                     if (cp != null) {
3441                         cp.setBackground(c);
3442                     }
3443                 }
3444             }
3445 
3446             public Color getForeground() {
3447                 AccessibleContext ac = getCurrentAccessibleContext();
3448                 if (ac instanceof AccessibleComponent) {
3449                     return ((AccessibleComponent) ac).getForeground();
3450                 } else {
3451                     Component c = getCurrentComponent();
3452                     if (c != null) {
3453                         return c.getForeground();
3454                     } else {
3455                         return null;
3456                     }
3457                 }
3458             }
3459 
3460             public void setForeground(Color c) {
3461                 AccessibleContext ac = getCurrentAccessibleContext();
3462                 if (ac instanceof AccessibleComponent) {
3463                     ((AccessibleComponent) ac).setForeground(c);
3464                 } else {
3465                     Component cp = getCurrentComponent();
3466                     if (cp != null) {
3467                         cp.setForeground(c);
3468                     }
3469                 }
3470             }
3471 
3472             public Cursor getCursor() {
3473                 AccessibleContext ac = getCurrentAccessibleContext();
3474                 if (ac instanceof AccessibleComponent) {
3475                     return ((AccessibleComponent) ac).getCursor();
3476                 } else {
3477                     Component c = getCurrentComponent();
3478                     if (c != null) {
3479                         return c.getCursor();
3480                     } else {
3481                         Accessible ap = getAccessibleParent();
3482                         if (ap instanceof AccessibleComponent) {
3483                             return ((AccessibleComponent) ap).getCursor();
3484                         } else {
3485                             return null;
3486                         }
3487                     }
3488                 }
3489             }
3490 
3491             public void setCursor(Cursor c) {
3492                 AccessibleContext ac = getCurrentAccessibleContext();
3493                 if (ac instanceof AccessibleComponent) {
3494                     ((AccessibleComponent) ac).setCursor(c);
3495                 } else {
3496                     Component cp = getCurrentComponent();
3497                     if (cp != null) {
3498                         cp.setCursor(c);
3499                     }
3500                 }
3501             }
3502 
3503             public Font getFont() {
3504                 AccessibleContext ac = getCurrentAccessibleContext();
3505                 if (ac instanceof AccessibleComponent) {
3506                     return ((AccessibleComponent) ac).getFont();
3507                 } else {
3508                     Component c = getCurrentComponent();
3509                     if (c != null) {
3510                         return c.getFont();
3511                     } else {
3512                         return null;
3513                     }
3514                 }
3515             }
3516 
3517             public void setFont(Font f) {
3518                 AccessibleContext ac = getCurrentAccessibleContext();
3519                 if (ac instanceof AccessibleComponent) {
3520                     ((AccessibleComponent) ac).setFont(f);
3521                 } else {
3522                     Component c = getCurrentComponent();
3523                     if (c != null) {
3524                         c.setFont(f);
3525                     }
3526                 }
3527             }
3528 
3529             public FontMetrics getFontMetrics(Font f) {
3530                 AccessibleContext ac = getCurrentAccessibleContext();
3531                 if (ac instanceof AccessibleComponent) {
3532                     return ((AccessibleComponent) ac).getFontMetrics(f);
3533                 } else {
3534                     Component c = getCurrentComponent();
3535                     if (c != null) {
3536                         return c.getFontMetrics(f);
3537                     } else {
3538                         return null;
3539                     }
3540                 }
3541             }
3542 
3543             public boolean isEnabled() {
3544                 AccessibleContext ac = getCurrentAccessibleContext();
3545                 if (ac instanceof AccessibleComponent) {
3546                     return ((AccessibleComponent) ac).isEnabled();
3547                 } else {
3548                     Component c = getCurrentComponent();
3549                     if (c != null) {
3550                         return c.isEnabled();
3551                     } else {
3552                         return false;
3553                     }
3554                 }
3555             }
3556 
3557             public void setEnabled(boolean b) {
3558                 AccessibleContext ac = getCurrentAccessibleContext();
3559                 if (ac instanceof AccessibleComponent) {
3560                     ((AccessibleComponent) ac).setEnabled(b);
3561                 } else {
3562                     Component c = getCurrentComponent();
3563                     if (c != null) {
3564                         c.setEnabled(b);
3565                     }
3566                 }
3567             }
3568 
3569             public boolean isVisible() {
3570                 int fi = parent.getFirstVisibleIndex();
3571                 int li = parent.getLastVisibleIndex();
3572                 // The UI incorrectly returns a -1 for the last
3573                 // visible index if the list is smaller than the
3574                 // viewport size.
3575                 if (li == -1) {
3576                     li = parent.getModel().getSize() - 1;
3577                 }
3578                 return ((indexInParent >= fi)
3579                         && (indexInParent <= li));
3580             }
3581 
3582             public void setVisible(boolean b) {
3583             }
3584 
3585             public boolean isShowing() {
3586                 return (parent.isShowing() && isVisible());
3587             }
3588 
3589             public boolean contains(Point p) {
3590                 AccessibleContext ac = getCurrentAccessibleContext();
3591                 if (ac instanceof AccessibleComponent) {
3592                     Rectangle r = ((AccessibleComponent) ac).getBounds();
3593                     return r.contains(p);
3594                 } else {
3595                     Component c = getCurrentComponent();
3596                     if (c != null) {
3597                         Rectangle r = c.getBounds();
3598                         return r.contains(p);
3599                     } else {
3600                         return getBounds().contains(p);
3601                     }
3602                 }
3603             }
3604 
3605             public Point getLocationOnScreen() {
3606                 if (parent != null) {
3607                     Point listLocation;
3608                     try {
3609                         listLocation = parent.getLocationOnScreen();
3610                     } catch (IllegalComponentStateException e) {
3611                         // This can happen if the component isn't visisble
3612                         return null;
3613                     }
3614                     Point componentLocation = parent.indexToLocation(indexInParent);
3615                     if (componentLocation != null) {
3616                         componentLocation.translate(listLocation.x, listLocation.y);
3617                         return componentLocation;
3618                     } else {
3619                         return null;
3620                     }
3621                 } else {
3622                     return null;
3623                 }
3624             }
3625 
3626             public Point getLocation() {
3627                 if (parent != null) {
3628                     return parent.indexToLocation(indexInParent);
3629                 } else {
3630                     return null;
3631                 }
3632             }
3633 
3634             public void setLocation(Point p) {
3635                 if ((parent != null)  && (parent.contains(p))) {
3636                     ensureIndexIsVisible(indexInParent);
3637                 }
3638             }
3639 
3640             public Rectangle getBounds() {
3641                 if (parent != null) {
3642                     return parent.getCellBounds(indexInParent,indexInParent);
3643                 } else {
3644                     return null;
3645                 }
3646             }
3647 
3648             public void setBounds(Rectangle r) {
3649                 AccessibleContext ac = getCurrentAccessibleContext();
3650                 if (ac instanceof AccessibleComponent) {
3651                     ((AccessibleComponent) ac).setBounds(r);
3652                 }
3653             }
3654 
3655             public Dimension getSize() {
3656                 Rectangle cellBounds = this.getBounds();
3657                 if (cellBounds != null) {
3658                     return cellBounds.getSize();
3659                 } else {
3660                     return null;
3661                 }
3662             }
3663 
3664             public void setSize (Dimension d) {
3665                 AccessibleContext ac = getCurrentAccessibleContext();
3666                 if (ac instanceof AccessibleComponent) {
3667                     ((AccessibleComponent) ac).setSize(d);
3668                 } else {
3669                     Component c = getCurrentComponent();
3670                     if (c != null) {
3671                         c.setSize(d);
3672                     }
3673                 }
3674             }
3675 
3676             public Accessible getAccessibleAt(Point p) {
3677                 AccessibleContext ac = getCurrentAccessibleContext();
3678                 if (ac instanceof AccessibleComponent) {
3679                     return ((AccessibleComponent) ac).getAccessibleAt(p);
3680                 } else {
3681                     return null;
3682                 }
3683             }
3684 
3685             @SuppressWarnings("deprecation")
3686             public boolean isFocusTraversable() {
3687                 AccessibleContext ac = getCurrentAccessibleContext();
3688                 if (ac instanceof AccessibleComponent) {
3689                     return ((AccessibleComponent) ac).isFocusTraversable();
3690                 } else {
3691                     Component c = getCurrentComponent();
3692                     if (c != null) {
3693                         return c.isFocusTraversable();
3694                     } else {
3695                         return false;
3696                     }
3697                 }
3698             }
3699 
3700             public void requestFocus() {
3701                 AccessibleContext ac = getCurrentAccessibleContext();
3702                 if (ac instanceof AccessibleComponent) {
3703                     ((AccessibleComponent) ac).requestFocus();
3704                 } else {
3705                     Component c = getCurrentComponent();
3706                     if (c != null) {
3707                         c.requestFocus();
3708                     }
3709                 }
3710             }
3711 
3712             public void addFocusListener(FocusListener l) {
3713                 AccessibleContext ac = getCurrentAccessibleContext();
3714                 if (ac instanceof AccessibleComponent) {
3715                     ((AccessibleComponent) ac).addFocusListener(l);
3716                 } else {
3717                     Component c = getCurrentComponent();
3718                     if (c != null) {
3719                         c.addFocusListener(l);
3720                     }
3721                 }
3722             }
3723 
3724             public void removeFocusListener(FocusListener l) {
3725                 AccessibleContext ac = getCurrentAccessibleContext();
3726                 if (ac instanceof AccessibleComponent) {
3727                     ((AccessibleComponent) ac).removeFocusListener(l);
3728                 } else {
3729                     Component c = getCurrentComponent();
3730                     if (c != null) {
3731                         c.removeFocusListener(l);
3732                     }
3733                 }
3734             }
3735 
3736             // TIGER - 4733624
3737             /**
3738              * Returns the icon for the element renderer, as the only item
3739              * of an array of <code>AccessibleIcon</code>s or a <code>null</code> array
3740              * if the renderer component contains no icons.
3741              *
3742              * @return an array containing the accessible icon
3743              *         or a <code>null</code> array if none
3744              * @since 1.3
3745              */
3746             public AccessibleIcon [] getAccessibleIcon() {
3747                 AccessibleContext ac = getCurrentAccessibleContext();
3748                 if (ac != null) {
3749                     return ac.getAccessibleIcon();
3750                 } else {
3751                     return null;
3752                 }
3753             }
3754 
3755             /**
3756              * {@inheritDoc}
3757              * @implSpec Returns the AccessibleAction for this AccessibleJListChild
3758              * as follows:  First getListCellRendererComponent of the ListCellRenderer
3759              * for the component at the "index in parent" of this child is called.
3760              * Then its AccessibleContext is fetched and that AccessibleContext's
3761              * AccessibleAction is returned.  Note that if an AccessibleAction
3762              * is not found using this process then this object with its implementation
3763              * of the AccessibleAction interface is returned.
3764              * @since 9
3765              */
3766             @Override
3767             public AccessibleAction getAccessibleAction() {
3768                 AccessibleContext ac = getCurrentAccessibleContext();
3769                 if (ac == null) {
3770                     return null;
3771                 } else {
3772                     AccessibleAction aa = ac.getAccessibleAction();
3773                     if (aa != null) {
3774                         return aa;
3775                     } else {
3776                         return this;
3777                     }
3778                 }
3779             }
3780 
3781             /**
3782              * {@inheritDoc}
3783              * @implSpec If i == 0 selects this AccessibleJListChild by calling
3784              * JList.this.setSelectedIndex(indexInParent) and then returns true;
3785              * otherwise returns false.
3786              * @since 9
3787              */
3788             @Override
3789             public boolean doAccessibleAction(int i) {
3790                 if (i == 0) {
3791                     JList.this.setSelectedIndex(indexInParent);
3792                     return true;
3793                 } else {
3794                     return false;
3795                 }
3796             }
3797 
3798             /**
3799              * {@inheritDoc}
3800              * @implSpec If i == 0 returns the action description fetched from
3801              * UIManager.getString("AbstractButton.clickText");
3802              * otherwise returns null.
3803              * @since 9
3804              */
3805             @Override
3806             public String getAccessibleActionDescription(int i) {
3807                 if (i == 0) {
3808                     return UIManager.getString("AbstractButton.clickText");
3809                 } else {
3810                     return null;
3811                 }
3812             }
3813 
3814             /**
3815              * {@inheritDoc}
3816              * @implSpec Returns 1, i.e. there is only one action.
3817              * @since 9
3818              */
3819             @Override
3820             public int getAccessibleActionCount() {
3821                 return 1;
3822             }
3823 
3824         } // inner class AccessibleJListChild
3825 
3826     } // inner class AccessibleJList
3827 }