How can we sort a JTable on a particular column in Java?

A JTable is a subclass of JComponent class for displaying complex data structures. A JTable component can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener interfaces. We can sort a JTable in a particular column by using the method setAutoCreateRowSorter() and set to true of JTable class.


import java.awt.*;
import javax.swing.*;
public final class JTableSorterTest extends JFrame {
   private JTable table;
   private JScrollPane scrollPane;
   public JTableSorterTest() {
      setTitle("JTableHeaderHide Test");
      String[] columnNames = {"Name", "Age", "City"};
      Object[][] data = {{"Raja", "35", "Hyderabad"}, {"Adithya", "25", "Chennai"}, {"Vineet", "23",       "Mumbai"}, {"Archana", "32", "Pune"}, {"Krishna", "30", "Kolkata"}};
      table = new JTable(data, columnNames);
      scrollPane= new JScrollPane(table);
      table.setAutoCreateRowSorter(true); // sorting of the rows on a particular column
      add(scrollPane, BorderLayout.CENTER);
      setSize(375, 250);
   public static void main(String[] args) {
      new JTableSorterTest();