JTable là một lớp con của JComponent hiển thị cấu trúc dữ liệu phức tạp. JTable tuân theo Model View Controller (MVC) để hiển thị dữ liệu theo hàng và cột. JTable tạo TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener. Chúng ta có thể sắp xếp JTable theo cột cụ thể bằng phương thức setAutoCreateRowSorter() đặt true của JTable.
Ví dụ
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); // Sắp xếp hàng theo cột cụ thể
add(scrollPane, BorderLayout.CENTER);
setSize(375, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new JTableSorterTest();
}
}
Kết quả
