JTable Sorting in JDK6 : JTable Sort « Swing « Java Tutorial






import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class JTableSortDemo {
  public static void main(String[] args) {
    Object[][] data = { { "A", 5 }, { "B", 2 }, { "C", 4 }, { "D", 8 } };
    String columnNames[] = { "Item", "Value" };
    TableModel model = new DefaultTableModel(data, columnNames) {
      public Class<?> getColumnClass(int column) {
        return getValueAt(0, column).getClass();
      }
    };
    JTable table = new JTable(model);

    TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    table.setRowSorter(sorter);

    JScrollPane scrollPane = new JScrollPane(table);
    JFrame frame = new JFrame("Sorting Table");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(scrollPane);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}








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.