< prev index next >

src/java.desktop/share/classes/javax/swing/JList.java

Print this page

        

@@ -2357,30 +2357,41 @@
     }
 
 
     /**
      * Selects the specified object from the list.
+     * If the object passed is not present in the list, the selection is
+     * cleared.
      *
      * @param anObject      the object to select
      * @param shouldScroll  {@code true} if the list should scroll to display
      *                      the selected object, if one exists; otherwise {@code false}
      */
     public void setSelectedValue(Object anObject,boolean shouldScroll) {
-        if(anObject == null)
-            setSelectedIndex(-1);
-        else if(!anObject.equals(getSelectedValue())) {
+        E selectedValue = getSelectedValue();
+        //This will be true if both anObject and selectedObject are either
+        // null or point to objects which return true on calling equals
+        if((anObject == selectedValue) ||
+                (anObject != null && anObject.equals(selectedValue))) {
+            return;
+        } else {
             int i,c;
             ListModel<E> dm = getModel();
-            for(i=0,c=dm.getSize();i<c;i++)
-                if(anObject.equals(dm.getElementAt(i))){
+            for(i=0,c=dm.getSize();i<c;i++) {
+                Object object  = dm.getElementAt(i);
+                //Either both should be null or reference to objects which
+                // return true with equals method
+                if ((anObject == object) ||
+                        anObject!= null && anObject.equals(object)) {
                     setSelectedIndex(i);
-                    if(shouldScroll)
+                    if (shouldScroll)
                         ensureIndexIsVisible(i);
                     repaint();  /** FIX-ME setSelectedIndex does not redraw all the time with the basic l&f**/
                     return;
                 }
-            setSelectedIndex(-1);
+            }
+            clearSelection();
         }
         repaint(); /** FIX-ME setSelectedIndex does not redraw all the time with the basic l&f**/
     }
 
 
< prev index next >