如何在 Java 中按特定列对 JTable 进行排序?
JTable 是用于显示复杂数据结构的JComponent 类的子类。JTable 组件可以遵循模型视图控制器 (MVC) 设计模式来显示行和列中的数据。JTable 可以生成TableModelListener、TableColumnModelListener、ListSelectionListener、CellEditorListener、RowSorterListener 接口。我们可以使用setAutoCreateRowSorter() 方法对 JTable 中的特定列进行排序,并将其设置为 JTable 类的true。
示例
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(); } }
输出
广告