Path: blob/master/src/java.desktop/share/classes/javax/swing/DefaultListSelectionModel.java
41153 views
/*1* Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package javax.swing;2627import java.util.EventListener;28import java.util.BitSet;29import java.io.Serializable;30import java.beans.Transient;3132import javax.swing.event.*;333435/**36* Default data model for list selections.37* <p>38* <strong>Warning:</strong>39* Serialized objects of this class will not be compatible with40* future Swing releases. The current serialization support is41* appropriate for short term storage or RMI between applications running42* the same version of Swing. As of 1.4, support for long term storage43* of all JavaBeans44* has been added to the <code>java.beans</code> package.45* Please see {@link java.beans.XMLEncoder}.46*47* @author Philip Milne48* @author Hans Muller49* @see ListSelectionModel50* @since 1.251*/52@SuppressWarnings("serial") // Same-version serialization only53public class DefaultListSelectionModel implements ListSelectionModel, Cloneable, Serializable54{55private static final int MIN = -1;56private static final int MAX = Integer.MAX_VALUE;57private int selectionMode = MULTIPLE_INTERVAL_SELECTION;58private int minIndex = MAX;59private int maxIndex = MIN;60private int anchorIndex = -1;61private int leadIndex = -1;62private int firstAdjustedIndex = MAX;63private int lastAdjustedIndex = MIN;64private boolean isAdjusting = false;6566private int firstChangedIndex = MAX;67private int lastChangedIndex = MIN;6869private BitSet value = new BitSet(32);70/**71* The list of listeners.72*/73protected EventListenerList listenerList = new EventListenerList();7475/**76* Whether or not the lead anchor notification is enabled.77*/78protected boolean leadAnchorNotificationEnabled = true;7980/**81* Constructs a {@code DefaultListSelectionModel}.82*/83public DefaultListSelectionModel() {}8485/** {@inheritDoc} */86public int getMinSelectionIndex() { return isSelectionEmpty() ? -1 : minIndex; }8788/** {@inheritDoc} */89public int getMaxSelectionIndex() { return maxIndex; }9091/** {@inheritDoc} */92public boolean getValueIsAdjusting() { return isAdjusting; }9394/** {@inheritDoc} */95public int getSelectionMode() { return selectionMode; }9697/**98* {@inheritDoc}99* @throws IllegalArgumentException {@inheritDoc}100*/101public void setSelectionMode(int selectionMode) {102int oldMode = this.selectionMode;103switch (selectionMode) {104case SINGLE_SELECTION:105case SINGLE_INTERVAL_SELECTION:106case MULTIPLE_INTERVAL_SELECTION:107this.selectionMode = selectionMode;108break;109default:110throw new IllegalArgumentException("invalid selectionMode");111}112113/*114This code will only be executed when selection needs to be updated on115changing selection mode. It will happen only if selection mode is changed116from MULTIPLE_INTERVAL to SINGLE_INTERVAL or SINGLE or from117SINGLE_INTERVAL to SINGLE118*/119if (oldMode > this.selectionMode) {120if (this.selectionMode == SINGLE_SELECTION) {121if (!isSelectionEmpty()) {122setSelectionInterval(minIndex, minIndex);123}124} else if (this.selectionMode == SINGLE_INTERVAL_SELECTION) {125if(!isSelectionEmpty()) {126int selectionEndindex = minIndex;127while (value.get(selectionEndindex + 1)) {128selectionEndindex++;129}130setSelectionInterval(minIndex, selectionEndindex);131}132}133}134}135136/** {@inheritDoc} */137public boolean isSelectedIndex(int index) {138return ((index < minIndex) || (index > maxIndex)) ? false : value.get(index);139}140141/** {@inheritDoc} */142public boolean isSelectionEmpty() {143return (minIndex > maxIndex);144}145146/** {@inheritDoc} */147public void addListSelectionListener(ListSelectionListener l) {148listenerList.add(ListSelectionListener.class, l);149}150151/** {@inheritDoc} */152public void removeListSelectionListener(ListSelectionListener l) {153listenerList.remove(ListSelectionListener.class, l);154}155156/**157* Returns an array of all the list selection listeners158* registered on this <code>DefaultListSelectionModel</code>.159*160* @return all of this model's <code>ListSelectionListener</code>s161* or an empty162* array if no list selection listeners are currently registered163*164* @see #addListSelectionListener165* @see #removeListSelectionListener166*167* @since 1.4168*/169public ListSelectionListener[] getListSelectionListeners() {170return listenerList.getListeners(ListSelectionListener.class);171}172173/**174* Notifies listeners that we have ended a series of adjustments.175* @param isAdjusting true if this is the final change in a series of176* adjustments177*/178protected void fireValueChanged(boolean isAdjusting) {179if (lastChangedIndex == MIN) {180return;181}182/* Change the values before sending the event to the183* listeners in case the event causes a listener to make184* another change to the selection.185*/186int oldFirstChangedIndex = firstChangedIndex;187int oldLastChangedIndex = lastChangedIndex;188firstChangedIndex = MAX;189lastChangedIndex = MIN;190fireValueChanged(oldFirstChangedIndex, oldLastChangedIndex, isAdjusting);191}192193194/**195* Notifies <code>ListSelectionListeners</code> that the value196* of the selection, in the closed interval <code>firstIndex</code>,197* <code>lastIndex</code>, has changed.198*199* @param firstIndex the first index in the interval200* @param lastIndex the last index in the interval201*/202protected void fireValueChanged(int firstIndex, int lastIndex) {203fireValueChanged(firstIndex, lastIndex, getValueIsAdjusting());204}205206/**207* @param firstIndex the first index in the interval208* @param lastIndex the last index in the interval209* @param isAdjusting true if this is the final change in a series of210* adjustments211* @see EventListenerList212*/213protected void fireValueChanged(int firstIndex, int lastIndex, boolean isAdjusting)214{215Object[] listeners = listenerList.getListenerList();216ListSelectionEvent e = null;217218for (int i = listeners.length - 2; i >= 0; i -= 2) {219if (listeners[i] == ListSelectionListener.class) {220if (e == null) {221e = new ListSelectionEvent(this, firstIndex, lastIndex, isAdjusting);222}223((ListSelectionListener)listeners[i+1]).valueChanged(e);224}225}226}227228private void fireValueChanged() {229if (lastAdjustedIndex == MIN) {230return;231}232/* If getValueAdjusting() is true, (eg. during a drag opereration)233* record the bounds of the changes so that, when the drag finishes (and234* setValueAdjusting(false) is called) we can post a single event235* with bounds covering all of these individual adjustments.236*/237if (getValueIsAdjusting()) {238firstChangedIndex = Math.min(firstChangedIndex, firstAdjustedIndex);239lastChangedIndex = Math.max(lastChangedIndex, lastAdjustedIndex);240}241/* Change the values before sending the event to the242* listeners in case the event causes a listener to make243* another change to the selection.244*/245int oldFirstAdjustedIndex = firstAdjustedIndex;246int oldLastAdjustedIndex = lastAdjustedIndex;247firstAdjustedIndex = MAX;248lastAdjustedIndex = MIN;249250fireValueChanged(oldFirstAdjustedIndex, oldLastAdjustedIndex);251}252253/**254* Returns an array of all the objects currently registered as255* <code><em>Foo</em>Listener</code>s256* upon this model.257* <code><em>Foo</em>Listener</code>s258* are registered using the <code>add<em>Foo</em>Listener</code> method.259* <p>260* You can specify the <code>listenerType</code> argument261* with a class literal, such as <code><em>Foo</em>Listener.class</code>.262* For example, you can query a <code>DefaultListSelectionModel</code>263* instance <code>m</code>264* for its list selection listeners265* with the following code:266*267* <pre>ListSelectionListener[] lsls = (ListSelectionListener[])(m.getListeners(ListSelectionListener.class));</pre>268*269* If no such listeners exist,270* this method returns an empty array.271*272* @param <T> the type of {@code EventListener} class being requested273* @param listenerType the type of listeners requested;274* this parameter should specify an interface275* that descends from <code>java.util.EventListener</code>276* @return an array of all objects registered as277* <code><em>Foo</em>Listener</code>s278* on this model,279* or an empty array if no such280* listeners have been added281* @exception ClassCastException if <code>listenerType</code> doesn't282* specify a class or interface that implements283* <code>java.util.EventListener</code>284*285* @see #getListSelectionListeners286*287* @since 1.3288*/289public <T extends EventListener> T[] getListeners(Class<T> listenerType) {290return listenerList.getListeners(listenerType);291}292293// Updates first and last change indices294private void markAsDirty(int r) {295if (r == -1) {296return;297}298299firstAdjustedIndex = Math.min(firstAdjustedIndex, r);300lastAdjustedIndex = Math.max(lastAdjustedIndex, r);301}302303// Sets the state at this index and update all relevant state.304private void set(int r) {305if (value.get(r)) {306return;307}308value.set(r);309markAsDirty(r);310311// Update minimum and maximum indices312minIndex = Math.min(minIndex, r);313maxIndex = Math.max(maxIndex, r);314}315316// Clears the state at this index and update all relevant state.317private void clear(int r) {318if (!value.get(r)) {319return;320}321value.clear(r);322markAsDirty(r);323324// Update minimum and maximum indices325/*326If (r > minIndex) the minimum has not changed.327The case (r < minIndex) is not possible because r'th value was set.328We only need to check for the case when lowest entry has been cleared,329and in this case we need to search for the first value set above it.330*/331if (r == minIndex) {332for(minIndex = minIndex + 1; minIndex <= maxIndex; minIndex++) {333if (value.get(minIndex)) {334break;335}336}337}338/*339If (r < maxIndex) the maximum has not changed.340The case (r > maxIndex) is not possible because r'th value was set.341We only need to check for the case when highest entry has been cleared,342and in this case we need to search for the first value set below it.343*/344if (r == maxIndex) {345for(maxIndex = maxIndex - 1; minIndex <= maxIndex; maxIndex--) {346if (value.get(maxIndex)) {347break;348}349}350}351/* Performance note: This method is called from inside a loop in352changeSelection() but we will only iterate in the loops353above on the basis of one iteration per deselected cell - in total.354Ie. the next time this method is called the work of the previous355deselection will not be repeated.356357We also don't need to worry about the case when the min and max358values are in their unassigned states. This cannot happen because359this method's initial check ensures that the selection was not empty360and therefore that the minIndex and maxIndex had 'real' values.361362If we have cleared the whole selection, set the minIndex and maxIndex363to their cannonical values so that the next set command always works364just by using Math.min and Math.max.365*/366if (isSelectionEmpty()) {367minIndex = MAX;368maxIndex = MIN;369}370}371372/**373* Sets the value of the leadAnchorNotificationEnabled flag.374*375* @param flag boolean value for {@code leadAnchorNotificationEnabled}376* @see #isLeadAnchorNotificationEnabled()377*/378public void setLeadAnchorNotificationEnabled(boolean flag) {379leadAnchorNotificationEnabled = flag;380}381382/**383* Returns the value of the <code>leadAnchorNotificationEnabled</code> flag.384* When <code>leadAnchorNotificationEnabled</code> is true the model385* generates notification events with bounds that cover all the changes to386* the selection plus the changes to the lead and anchor indices.387* Setting the flag to false causes a narrowing of the event's bounds to388* include only the elements that have been selected or deselected since389* the last change. Either way, the model continues to maintain the lead390* and anchor variables internally. The default is true.391* <p>392* Note: It is possible for the lead or anchor to be changed without a393* change to the selection. Notification of these changes is often394* important, such as when the new lead or anchor needs to be updated in395* the view. Therefore, caution is urged when changing the default value.396*397* @return the value of the <code>leadAnchorNotificationEnabled</code> flag398* @see #setLeadAnchorNotificationEnabled(boolean)399*/400public boolean isLeadAnchorNotificationEnabled() {401return leadAnchorNotificationEnabled;402}403404private void updateLeadAnchorIndices(int anchorIndex, int leadIndex) {405if (leadAnchorNotificationEnabled) {406if (this.anchorIndex != anchorIndex) {407markAsDirty(this.anchorIndex);408markAsDirty(anchorIndex);409}410411if (this.leadIndex != leadIndex) {412markAsDirty(this.leadIndex);413markAsDirty(leadIndex);414}415}416this.anchorIndex = anchorIndex;417this.leadIndex = leadIndex;418}419420private boolean contains(int a, int b, int i) {421return (i >= a) && (i <= b);422}423424private void changeSelection(int clearMin, int clearMax,425int setMin, int setMax, boolean clearFirst) {426for(int i = Math.min(setMin, clearMin); i <= Math.max(setMax, clearMax); i++) {427428boolean shouldClear = contains(clearMin, clearMax, i);429boolean shouldSet = contains(setMin, setMax, i);430431if (shouldSet && shouldClear) {432if (clearFirst) {433shouldClear = false;434}435else {436shouldSet = false;437}438}439440if (shouldSet) {441set(i);442}443if (shouldClear) {444clear(i);445}446}447fireValueChanged();448}449450/**451* Change the selection with the effect of first clearing the values452* in the inclusive range [clearMin, clearMax] then setting the values453* in the inclusive range [setMin, setMax]. Do this in one pass so454* that no values are cleared if they would later be set.455*/456private void changeSelection(int clearMin, int clearMax, int setMin, int setMax) {457changeSelection(clearMin, clearMax, setMin, setMax, true);458}459460/** {@inheritDoc} */461public void clearSelection() {462removeSelectionIntervalImpl(minIndex, maxIndex, false);463}464465/**466* Changes the selection to be between {@code index0} and {@code index1}467* inclusive. {@code index0} doesn't have to be less than or equal to468* {@code index1}.469* <p>470* In {@code SINGLE_SELECTION} selection mode, only the second index471* is used.472* <p>473* If this represents a change to the current selection, then each474* {@code ListSelectionListener} is notified of the change.475* <p>476* If either index is {@code -1}, this method does nothing and returns477* without exception. Otherwise, if either index is less than {@code -1},478* an {@code IndexOutOfBoundsException} is thrown.479*480* @param index0 one end of the interval.481* @param index1 other end of the interval482* @throws IndexOutOfBoundsException if either index is less than {@code -1}483* (and neither index is {@code -1})484* @see #addListSelectionListener485*/486public void setSelectionInterval(int index0, int index1) {487if (index0 == -1 || index1 == -1) {488return;489}490491if (getSelectionMode() == SINGLE_SELECTION) {492index0 = index1;493}494495updateLeadAnchorIndices(index0, index1);496497int clearMin = minIndex;498int clearMax = maxIndex;499int setMin = Math.min(index0, index1);500int setMax = Math.max(index0, index1);501changeSelection(clearMin, clearMax, setMin, setMax);502}503504/**505* Changes the selection to be the set union of the current selection506* and the indices between {@code index0} and {@code index1} inclusive.507* <p>508* In {@code SINGLE_SELECTION} selection mode, this is equivalent509* to calling {@code setSelectionInterval}, and only the second index510* is used. In {@code SINGLE_INTERVAL_SELECTION} selection mode, this511* method behaves like {@code setSelectionInterval}, unless the given512* interval is immediately adjacent to or overlaps the existing selection,513* and can therefore be used to grow it.514* <p>515* If this represents a change to the current selection, then each516* {@code ListSelectionListener} is notified of the change. Note that517* {@code index0} doesn't have to be less than or equal to {@code index1}.518* <p>519* If either index is {@code -1}, this method does nothing and returns520* without exception. Otherwise, if either index is less than {@code -1},521* an {@code IndexOutOfBoundsException} is thrown.522*523* @param index0 one end of the interval.524* @param index1 other end of the interval525* @throws IndexOutOfBoundsException if either index is less than {@code -1}526* (and neither index is {@code -1})527* @see #addListSelectionListener528* @see #setSelectionInterval529*/530public void addSelectionInterval(int index0, int index1)531{532if (index0 == -1 || index1 == -1) {533return;534}535536// If we only allow a single selection, channel through537// setSelectionInterval() to enforce the rule.538if (getSelectionMode() == SINGLE_SELECTION) {539setSelectionInterval(index0, index1);540return;541}542543updateLeadAnchorIndices(index0, index1);544545int clearMin = MAX;546int clearMax = MIN;547int setMin = Math.min(index0, index1);548int setMax = Math.max(index0, index1);549550// If we only allow a single interval and this would result551// in multiple intervals, then set the selection to be just552// the new range.553if (getSelectionMode() == SINGLE_INTERVAL_SELECTION &&554(setMax < minIndex - 1 || setMin > maxIndex + 1)) {555556setSelectionInterval(index0, index1);557return;558}559560changeSelection(clearMin, clearMax, setMin, setMax);561}562563564/**565* Changes the selection to be the set difference of the current selection566* and the indices between {@code index0} and {@code index1} inclusive.567* {@code index0} doesn't have to be less than or equal to {@code index1}.568* <p>569* In {@code SINGLE_INTERVAL_SELECTION} selection mode, if the removal570* would produce two disjoint selections, the removal is extended through571* the greater end of the selection. For example, if the selection is572* {@code 0-10} and you supply indices {@code 5,6} (in any order) the573* resulting selection is {@code 0-4}.574* <p>575* If this represents a change to the current selection, then each576* {@code ListSelectionListener} is notified of the change.577* <p>578* If either index is {@code -1}, this method does nothing and returns579* without exception. Otherwise, if either index is less than {@code -1},580* an {@code IndexOutOfBoundsException} is thrown.581*582* @param index0 one end of the interval583* @param index1 other end of the interval584* @throws IndexOutOfBoundsException if either index is less than {@code -1}585* (and neither index is {@code -1})586* @see #addListSelectionListener587*/588public void removeSelectionInterval(int index0, int index1)589{590removeSelectionIntervalImpl(index0, index1, true);591}592593// private implementation allowing the selection interval594// to be removed without affecting the lead and anchor595private void removeSelectionIntervalImpl(int index0, int index1,596boolean changeLeadAnchor) {597598if (index0 == -1 || index1 == -1) {599return;600}601602if (changeLeadAnchor) {603updateLeadAnchorIndices(index0, index1);604}605606int clearMin = Math.min(index0, index1);607int clearMax = Math.max(index0, index1);608int setMin = MAX;609int setMax = MIN;610611// If the removal would produce to two disjoint selections in a mode612// that only allows one, extend the removal to the end of the selection.613if (getSelectionMode() != MULTIPLE_INTERVAL_SELECTION &&614clearMin > minIndex && clearMax < maxIndex) {615clearMax = maxIndex;616}617618changeSelection(clearMin, clearMax, setMin, setMax);619}620621private void setState(int index, boolean state) {622if (state) {623set(index);624}625else {626clear(index);627}628}629630/**631* Insert length indices beginning before/after index. If the value632* at index is itself selected and the selection mode is not633* SINGLE_SELECTION, set all of the newly inserted items as selected.634* Otherwise leave them unselected. This method is typically635* called to sync the selection model with a corresponding change636* in the data model.637*/638public void insertIndexInterval(int index, int length, boolean before)639{640/* The first new index will appear at insMinIndex and the last641* one will appear at insMaxIndex642*/643int insMinIndex = (before) ? index : index + 1;644int insMaxIndex = (insMinIndex + length) - 1;645646/* Right shift the entire bitset by length, beginning with647* index-1 if before is true, index+1 if it's false (i.e. with648* insMinIndex).649*/650for(int i = maxIndex; i >= insMinIndex; i--) {651setState(i + length, value.get(i));652}653654/* Initialize the newly inserted indices.655*/656boolean setInsertedValues = ((getSelectionMode() == SINGLE_SELECTION) ?657false : value.get(index));658for(int i = insMinIndex; i <= insMaxIndex; i++) {659setState(i, setInsertedValues);660}661662int leadIndex = this.leadIndex;663if (leadIndex > index || (before && leadIndex == index)) {664leadIndex = this.leadIndex + length;665}666int anchorIndex = this.anchorIndex;667if (anchorIndex > index || (before && anchorIndex == index)) {668anchorIndex = this.anchorIndex + length;669}670if (leadIndex != this.leadIndex || anchorIndex != this.anchorIndex) {671updateLeadAnchorIndices(anchorIndex, leadIndex);672}673674fireValueChanged();675}676677678/**679* Remove the indices in the interval index0,index1 (inclusive) from680* the selection model. This is typically called to sync the selection681* model width a corresponding change in the data model. Note682* that (as always) index0 need not be <= index1.683*/684public void removeIndexInterval(int index0, int index1)685{686int rmMinIndex = Math.min(index0, index1);687int rmMaxIndex = Math.max(index0, index1);688int gapLength = (rmMaxIndex - rmMinIndex) + 1;689690/* Shift the entire bitset to the left to close the index0, index1691* gap.692*/693for(int i = rmMinIndex; i <= maxIndex; i++) {694setState(i, value.get(i + gapLength));695}696697int leadIndex = this.leadIndex;698if (leadIndex == 0 && rmMinIndex == 0) {699// do nothing700} else if (leadIndex > rmMaxIndex) {701leadIndex = this.leadIndex - gapLength;702} else if (leadIndex >= rmMinIndex) {703leadIndex = rmMinIndex - 1;704}705706int anchorIndex = this.anchorIndex;707if (anchorIndex == 0 && rmMinIndex == 0) {708// do nothing709} else if (anchorIndex > rmMaxIndex) {710anchorIndex = this.anchorIndex - gapLength;711} else if (anchorIndex >= rmMinIndex) {712anchorIndex = rmMinIndex - 1;713}714715if (leadIndex != this.leadIndex || anchorIndex != this.anchorIndex) {716updateLeadAnchorIndices(anchorIndex, leadIndex);717}718719fireValueChanged();720}721722723/** {@inheritDoc} */724public void setValueIsAdjusting(boolean isAdjusting) {725if (isAdjusting != this.isAdjusting) {726this.isAdjusting = isAdjusting;727this.fireValueChanged(isAdjusting);728}729}730731732/**733* Returns a string that displays and identifies this734* object's properties.735*736* @return a <code>String</code> representation of this object737*/738public String toString() {739String s = ((getValueIsAdjusting()) ? "~" : "=") + value.toString();740return getClass().getName() + " " + Integer.toString(hashCode()) + " " + s;741}742743/**744* Returns a clone of this selection model with the same selection.745* <code>listenerLists</code> are not duplicated.746*747* @exception CloneNotSupportedException if the selection model does not748* both (a) implement the Cloneable interface and (b) define a749* <code>clone</code> method.750*/751public Object clone() throws CloneNotSupportedException {752DefaultListSelectionModel clone = (DefaultListSelectionModel)super.clone();753clone.value = (BitSet)value.clone();754clone.listenerList = new EventListenerList();755return clone;756}757758/** {@inheritDoc} */759@Transient760public int getAnchorSelectionIndex() {761return anchorIndex;762}763764/** {@inheritDoc} */765@Transient766public int getLeadSelectionIndex() {767return leadIndex;768}769770/**771* Set the anchor selection index, leaving all selection values unchanged.772* If leadAnchorNotificationEnabled is true, send a notification covering773* the old and new anchor cells.774*775* @see #getAnchorSelectionIndex776* @see #setLeadSelectionIndex777*/778public void setAnchorSelectionIndex(int anchorIndex) {779updateLeadAnchorIndices(anchorIndex, this.leadIndex);780fireValueChanged();781}782783/**784* Set the lead selection index, leaving all selection values unchanged.785* If leadAnchorNotificationEnabled is true, send a notification covering786* the old and new lead cells.787*788* @param leadIndex the new lead selection index789*790* @see #setAnchorSelectionIndex791* @see #setLeadSelectionIndex792* @see #getLeadSelectionIndex793*794* @since 1.5795*/796public void moveLeadSelectionIndex(int leadIndex) {797// disallow a -1 lead unless the anchor is already -1798if (leadIndex == -1) {799if (this.anchorIndex != -1) {800return;801}802803/* PENDING(shannonh) - The following check is nice, to be consistent with804setLeadSelectionIndex. However, it is not absolutely805necessary: One could work around it by setting the anchor806to something valid, modifying the lead, and then moving807the anchor back to -1. For this reason, there's no sense808in adding it at this time, as that would require809updating the spec and officially committing to it.810811// otherwise, don't do anything if the anchor is -1812} else if (this.anchorIndex == -1) {813return;814*/815816}817818updateLeadAnchorIndices(this.anchorIndex, leadIndex);819fireValueChanged();820}821822/**823* Sets the lead selection index, ensuring that values between the824* anchor and the new lead are either all selected or all deselected.825* If the value at the anchor index is selected, first clear all the826* values in the range [anchor, oldLeadIndex], then select all the values827* values in the range [anchor, newLeadIndex], where oldLeadIndex is the old828* leadIndex and newLeadIndex is the new one.829* <p>830* If the value at the anchor index is not selected, do the same thing in831* reverse selecting values in the old range and deselecting values in the832* new one.833* <p>834* Generate a single event for this change and notify all listeners.835* For the purposes of generating minimal bounds in this event, do the836* operation in a single pass; that way the first and last index inside the837* ListSelectionEvent that is broadcast will refer to cells that actually838* changed value because of this method. If, instead, this operation were839* done in two steps the effect on the selection state would be the same840* but two events would be generated and the bounds around the changed841* values would be wider, including cells that had been first cleared only842* to later be set.843* <p>844* This method can be used in the <code>mouseDragged</code> method845* of a UI class to extend a selection.846*847* @see #getLeadSelectionIndex848* @see #setAnchorSelectionIndex849*/850public void setLeadSelectionIndex(int leadIndex) {851int anchorIndex = this.anchorIndex;852853// only allow a -1 lead if the anchor is already -1854if (leadIndex == -1) {855if (anchorIndex == -1) {856updateLeadAnchorIndices(anchorIndex, leadIndex);857fireValueChanged();858}859860return;861// otherwise, don't do anything if the anchor is -1862} else if (anchorIndex == -1) {863return;864}865866if (this.leadIndex == -1) {867this.leadIndex = leadIndex;868}869870boolean shouldSelect = value.get(this.anchorIndex);871872if (getSelectionMode() == SINGLE_SELECTION) {873anchorIndex = leadIndex;874shouldSelect = true;875}876877int oldMin = Math.min(this.anchorIndex, this.leadIndex);878int oldMax = Math.max(this.anchorIndex, this.leadIndex);879int newMin = Math.min(anchorIndex, leadIndex);880int newMax = Math.max(anchorIndex, leadIndex);881882updateLeadAnchorIndices(anchorIndex, leadIndex);883884if (shouldSelect) {885changeSelection(oldMin, oldMax, newMin, newMax);886}887else {888changeSelection(newMin, newMax, oldMin, oldMax, false);889}890}891}892893894