JTable เป็น subclass ของ JComponent สำหรับแสดงโครงสร้างข้อมูลซับซ้อน JTable component ปฏิบัติตาม Model View Controller (MVC) design pattern แสดงข้อมูลใน rows และ columns JTable สร้าง TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener interfaces เราสามารถ sort JTable ใน column เฉพาะได้โดยใช้เมธอด setAutoCreateRowSorter() ตั้งค่า true ของคลาส JTable
ตัวอย่าง
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 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
