KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > jawe > xml > panels > tablesorting > SortingTableModel


1 package org.enhydra.jawe.xml.panels.tablesorting;
2
3 import java.util.Collections JavaDoc;
4 import java.util.Comparator JavaDoc;
5 import java.util.Vector JavaDoc;
6 import javax.swing.table.DefaultTableModel JavaDoc;
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 JavaDoc {
12
13    XMLCollection owner;
14
15    public SortingTableModel(XMLCollection c,Vector JavaDoc data, Vector JavaDoc names) {
16       super(data, names);
17       this.owner=c;
18    }
19
20    public void sortByColumn(int col, boolean ascending) {
21       Vector JavaDoc dv=getDataVector();
22       Vector JavaDoc v=new Vector JavaDoc(dv);
23       int vs=v.size();
24       for (int i=vs-1; i>=0; i--) {
25          XMLElement el=(XMLElement)((Vector JavaDoc)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 JavaDoc {
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 JavaDoc first, Object JavaDoc second) {
54          if (first instanceof Vector JavaDoc && second instanceof Vector JavaDoc) {
55             String JavaDoc str1 = ((Vector JavaDoc)first).elementAt(index).toString();
56             String JavaDoc str2 = ((Vector JavaDoc)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