1 6 7 package org.jdesktop.swing.binding; 8 9 import javax.swing.ListSelectionModel ; 10 import javax.swing.event.ListSelectionEvent ; 11 import javax.swing.event.ListSelectionListener ; 12 import org.jdesktop.swing.data.SelectionModel; 13 import org.jdesktop.swing.data.SelectionModelEvent; 14 import org.jdesktop.swing.data.SelectionModelListener; 15 16 20 public class ListSelectionBinding extends SelectionBinding { 21 private boolean indexIsChanging = false; 22 23 24 public ListSelectionBinding(final SelectionModel sm, final ListSelectionModel lsm) { 25 super(sm); 26 27 lsm.addListSelectionListener(new ListSelectionListener () { 30 public void valueChanged(ListSelectionEvent e) { 31 if (!e.getValueIsAdjusting() && !indexIsChanging) { 32 sm.setSelectionIndices(getSelectedIndices(lsm)); 33 } 34 } 35 }); 36 sm.addSelectionModelListener(new SelectionModelListener() { 40 public void selectionChanged(SelectionModelEvent evt) { 41 indexIsChanging = true; 42 setSelectedIndices(sm.getSelectionIndices(), lsm); 43 indexIsChanging = false; 44 } 45 }); 46 } 47 48 private int[] getSelectedIndices(ListSelectionModel sm) { 49 int iMin = sm.getMinSelectionIndex(); 50 int iMax = sm.getMaxSelectionIndex(); 51 52 if ((iMin < 0) || (iMax < 0)) { 53 return new int[0]; 54 } 55 56 int[] rvTmp = new int[1+ (iMax - iMin)]; 57 int n = 0; 58 for(int i = iMin; i <= iMax; i++) { 59 if (sm.isSelectedIndex(i)) { 60 rvTmp[n++] = i; 61 } 62 } 63 int[] rv = new int[n]; 64 System.arraycopy(rvTmp, 0, rv, 0, n); 65 return rv; 66 } 67 68 69 private void setSelectedIndices(int[] indices, ListSelectionModel sm) { 70 sm.clearSelection(); 71 for(int i = 0; i < indices.length; i++) { 72 sm.addSelectionInterval(indices[i], indices[i]); 73 } 74 } 75 } 76 | Popular Tags |