Terai Atsuhiro 2024-04-18 (木) 14:47:21

SortableTableExample

http://terai.s55.xrea.com/swing/sortabletable/screenshot.png

class SortableTableModel extends DefaultTableModel{
  public SortableTableModel(String[] str, int row){
    super(str, row);
  }
  public void sortByColumn(int column, boolean isAscent){
    Collections.sort(getDataVector(), new ColumnComparator(column, isAscent));
    fireTableDataChanged();
  }
}
class ColumnComparator implements Comparator{
  final protected int index;
  final protected boolean ascending;
  public ColumnComparator(int index, boolean ascending){
    this.index = index;
    this.ascending = ascending;
  }
  public int compare(Object one, Object two){
    if(one instanceof Vector && two instanceof Vector){
      Object oOne = ((Vector)one).elementAt(index);
      Object oTwo = ((Vector)two).elementAt(index);
      if(oOne==null && oTwo==null){
        return 0;
      }else if(oOne==null){
        return ascending ? -1 :  1;
      }else if(oTwo==null){
        return ascending ?  1 : -1;
      }else if(oOne instanceof Comparable && oTwo instanceof Comparable){
        Comparable cOne = (Comparable)oOne;
        Comparable cTwo = (Comparable)oTwo;
        return ascending ? cOne.compareTo(cTwo) : cTwo.compareTo(cOne);
      }
    }
    return 1;
  }
  public int compare(Number o1, Number o2){
    double n1 = o1.doubleValue();
    double n2 = o2.doubleValue();
    if(n1 < n2){
      return -1;
    }else if(n1 > n2){
      return 1;
    }else{
      return 0;
    }
  }
}

Swing/TableSorter