import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
public class JTableSortDemo {
public static void main(String[] args) {
//Object[][] data = {{"A",5},{"B",2},{"C",4},{"D",8}};//大写字母加数字
//Object[][] data = {{"A","5"},{"B","2"},{"C","4"},{"D","8"}};//大写字母加String
//Object[][] data = {{"a","5"},{"b","2"},{"c","4"},{"d","8"}};//小写字母
Object[][] data = {{"你","5"},{"我","2"},{"他","4"},{"谁","8"}};//中文也可以排序
String columnNames[] = {"名称","数值"};
//TableModel model = new DefaultTableModel(data,columnNames);
TableModel model = new DefaultTableModel(data,columnNames){
public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
JTable table = new JTable(model);
/**
* 1.必须为 TableModel 的一个实现,所以我们把model一开始定义为TableModel
* 2.它使用 TableModel 提供排序和过滤操作。
* 3.除了排序操作,TableRowSorter 还提供过滤操作。使用 setFilter 方法指定过滤器。
*/
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
table.setRowSorter(sorter);
JScrollPane scrollPane = new JScrollPane(table);
JFrame frame = new JFrame("表格排序");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.setSize(300, 200);
frame.setVisible(true);
}
}