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.
Example
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);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new JTableSorterTest();
}
}Output
