Sorting a Column in a JTable Component : JTable Sort « Swing « Java Tutorial






import java.util.Arrays;
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);

    boolean ascending = false;
    Vector data = model.getDataVector();
    Object[] colData = new Object[model.getRowCount()];

    for (int i = 0; i < colData.length; i++) {
      colData[i] = ((Vector) data.get(i)).get(0);
    }
    Arrays.sort(colData, new ColumnSorter());
    for (int i = 0; i < colData.length; i++) {
      ((Vector) data.get(i)).set(0, colData[i]);
    }
    model.fireTableStructureChanged();
  }
}

class ColumnSorter implements Comparator {
  ColumnSorter() {
  }

  public int compare(Object a, Object b) {
    if (a instanceof String && ((String) a).length() == 0) {
      a = null;
    }
    if (b instanceof String && ((String) b).length() == 0) {
      b = null;
    }
    if (a == null && b == null) {
      return 0;
    } else if (a == null) {
      return 1;
    } else if (b == null) {
      return -1;
    } else if (a instanceof Comparable) {
      return ((Comparable) a).compareTo(b);
    } else {
      return a.toString().compareTo(b.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.