1 package org.enhydra.jawe.xml.panels.tablesorting; 2 3 import java.util.Collections ; 4 import java.util.Comparator ; 5 import java.util.Vector ; 6 import javax.swing.table.DefaultTableModel ; 7 import org.enhydra.jawe.xml.XMLCollection; 8 import org.enhydra.jawe.xml.XMLCollectionElement; 9 import org.enhydra.jawe.xml.XMLElement; 10 11 public class SortingTableModel extends DefaultTableModel { 12 13 XMLCollection owner; 14 15 public SortingTableModel(XMLCollection c,Vector data, Vector names) { 16 super(data, names); 17 this.owner=c; 18 } 19 20 public void sortByColumn(int col, boolean ascending) { 21 Vector dv=getDataVector(); 22 Vector v=new Vector (dv); 23 int vs=v.size(); 24 for (int i=vs-1; i>=0; i--) { 25 XMLElement el=(XMLElement)((Vector )v.elementAt(i)).elementAt(0); 26 if (el instanceof XMLCollectionElement) { 27 XMLCollectionElement cel=(XMLCollectionElement)el; 28 XMLCollection celOwner=cel.getCollection(); 29 if (celOwner==null || !celOwner.equals(owner)) { 30 v.remove(i); 31 } 32 } 33 } 34 vs=v.size(); 35 if (vs>0) { 36 Collections.sort(v,new ColumnSortingComparator(col, ascending)); 37 for (int i=0; i<vs; i++) { 38 dv.set(i,v.get(i)); 39 } 40 } 41 } 42 43 static class ColumnSortingComparator implements Comparator { 44 45 protected int index; 46 protected boolean ascending; 47 48 public ColumnSortingComparator(int index, boolean ascending) { 49 this.index = index; 50 this.ascending = ascending; 51 } 52 53 public int compare(Object first, Object second) { 54 if (first instanceof Vector && second instanceof Vector ) { 55 String str1 = ((Vector )first).elementAt(index).toString(); 56 String str2 = ((Vector )second).elementAt(index).toString(); 57 if (ascending) { 58 return str1.compareTo(str2); 59 } else { 60 return str2.compareTo(str1); 61 } 62 } 63 64 return 1; 65 } 66 67 } 68 } 69 | Popular Tags |