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