Sorting the Rows in a JTable Component Based on a Column : JTable Sort « Swing « Java Tutorial






import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class Main {
  public static void main(String[] argv) throws Exception {

    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    table.setAutoCreateColumnsFromModel(false);

    Vector data = model.getDataVector();
    Collections.sort(data, new ColumnSorter(0));
    model.fireTableStructureChanged();
  }
}

class ColumnSorter implements Comparator {
  int colIndex;

  ColumnSorter(int colIndex) {
    this.colIndex = colIndex;
  }

  public int compare(Object a, Object b) {
    Vector v1 = (Vector) a;
    Vector v2 = (Vector) b;
    Object o1 = v1.get(colIndex);
    Object o2 = v2.get(colIndex);

    if (o1 instanceof String && ((String) o1).length() == 0) {
      o1 = null;
    }
    if (o2 instanceof String && ((String) o2).length() == 0) {
      o2 = null;
    }

    if (o1 == null && o2 == null) {
      return 0;
    } else if (o1 == null) {
      return 1;
    } else if (o2 == null) {
      return -1;
    } else if (o1 instanceof Comparable) {

      return ((Comparable) o1).compareTo(o2);
    } else {

      return o1.toString().compareTo(o2.toString());
    }
  }
}








14.63.JTable Sort
14.63.1.JTable Sorting in JDK6
14.63.2.Using RowSorter to sort a JTable
14.63.3.TableRowSorter with column classTableRowSorter with column class
14.63.4.TableRowSorter without column classTableRowSorter without column class
14.63.5.Sorting the Rows in a JTable Component Based on a Column
14.63.6.Sorting a Column in a JTable Component
14.63.7.Sorting and Filtering Tables
14.63.8.Sorting JTable Elements
14.63.9.A simple extension of JTable that supports the use of a SortableTableModel.