KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jdesktop > swing > binding > ListSelectionBinding


1 /*
2  * ListSelectionBinding.java
3  *
4  * Created on February 24, 2005, 6:33 AM
5  */

6
7 package org.jdesktop.swing.binding;
8
9 import javax.swing.ListSelectionModel JavaDoc;
10 import javax.swing.event.ListSelectionEvent JavaDoc;
11 import javax.swing.event.ListSelectionListener JavaDoc;
12 import org.jdesktop.swing.data.SelectionModel;
13 import org.jdesktop.swing.data.SelectionModelEvent;
14 import org.jdesktop.swing.data.SelectionModelListener;
15
16 /**
17  *
18  * @author rb156199
19  */

20 public class ListSelectionBinding extends SelectionBinding {
21     private boolean indexIsChanging = false;
22
23     /** Creates a new instance of ListSelectionBinding */
24     public ListSelectionBinding(final SelectionModel JavaDoc sm, final ListSelectionModel JavaDoc lsm) {
25         super(sm);
26         
27         //listen for changes in the list selection and maintain the
28
//synchronicity with the selection model
29
lsm.addListSelectionListener(new ListSelectionListener JavaDoc() {
30             public void valueChanged(ListSelectionEvent JavaDoc e) {
31                 if (!e.getValueIsAdjusting() && !indexIsChanging) {
32                     sm.setSelectionIndices(getSelectedIndices(lsm));
33                 }
34             }
35         });
36         //add a property change listener to listen for selection change events
37
//in the selection model. Set the currently selected row(s) to be the
38
//same as the current row(s) in the selection model
39
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 JavaDoc 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 JavaDoc 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