1. package org.jr.swing.table;
  2. /**
  3. * Copyright: Copyright (c) 2002-2004
  4. * Company: JavaResearch(http://www.javaresearch.org)
  5. * 最后更新日期:2003年3月1日
  6. * @author Cherami
  7. */
  8. import java.util.*;
  9. import org.jr.util.*;
  10. /**
  11. * 表格排序器。
  12. * @since 0.1
  13. */
  14. public class TableSorter {
  15. SortableTableModel model;
  16. /**
  17. * 根据指定的可排序表格模型构造一个TableSorter。
  18. * @param model 可排序表格模型
  19. * @since 0.1
  20. */
  21. public TableSorter(SortableTableModel model) {
  22. this.model = model;
  23. }
  24. /**
  25. * 排序。
  26. * @param column 要排序的列
  27. * @param isAscent 排序方式
  28. * @since 0.1
  29. */
  30. public void sort(int column, boolean isAscent) {
  31. int n = model.getRowCount();
  32. int[] indexes = model.getIndexes();
  33. for (int i = 0; i < n - 1; i++) {
  34. int k = i;
  35. for (int j = i + 1; j < n; j++) {
  36. if (isAscent) {
  37. if (compare(column, j, k) < 0) {
  38. k = j;
  39. }
  40. }
  41. else {
  42. if (compare(column, j, k) > 0) {
  43. k = j;
  44. }
  45. }
  46. }
  47. int tmp = indexes[i];
  48. indexes[i] = indexes[k];
  49. indexes[k] = tmp;
  50. }
  51. }
  52. /**
  53. * 比较指定列的两行的大小。
  54. * @param column 要比较的列
  55. * @param row1 第一行
  56. * @param row2 第二行
  57. * @return 第一个值大于第二个值则返回1,等于则等于0,否则返回-1。
  58. * @since 0.1
  59. */
  60. public int compare(int column, int row1, int row2) {
  61. Object o1 = model.getValueAt(row1, column);
  62. Object o2 = model.getValueAt(row2, column);
  63. if (o1 == null && o2 == null) {
  64. return 0;
  65. }
  66. else if (o1 == null) {
  67. return -1;
  68. }
  69. else if (o2 == null) {
  70. return 1;
  71. }
  72. else {
  73. Class type = model.getColumnClass(column);
  74. if (ClassUtil.isSubclass(Number.class, type)) {
  75. return CompareUtil.compare( (Number) o1, (Number) o2);
  76. }
  77. else if (type == String.class) {
  78. return ( (String) o1).compareTo( (String) o2);
  79. }
  80. else if (ClassUtil.isSubclass(Date.class, type)) {
  81. return ( (Date) o1).compareTo( (Date) o2);
  82. }
  83. else if (type == Boolean.class) {
  84. return CompareUtil.compare( (Boolean) o1, (Boolean) o2);
  85. }
  86. else {
  87. return ( (String) o1).compareTo( (String) o2);
  88. }
  89. }
  90. }
  91. }