用于 ASC/DESC 的 Java SE 6 箭头位于标题文本上方(客户必须拥有)
我用来在标题文本上方显示箭头:
TableRowSorter sorter = new TableRowSorter();
sorter.setModel(table.getModel());
table.setRowSorter(sorter);
或者
table.setAutoCreateRowSorter(true);
ASC/DESC 的箭头在 Header-Text 上方,没错。我想使用自己的比较器,但在我的示例中,调用了比较器,但它不起作用。什么代码要更改为通过我自己的比较器对表格行进行排序,并在标题文本排序 asc/desc 上方使用箭头?
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class JTableExample extends JFrame {
private JTable table;
private FooTableModel model;
public JTableExample() {
super("JTableExample");
setDefaultCloseOperation(EXIT_ON_CLOSE);
String plaf = UIManager.getSystemLookAndFeelClassName();
try {
UIManager.setLookAndFeel(plaf);
}
catch (ClassNotFoundException e) {}
catch (InstantiationException e) {}
catch (IllegalAccessException e) {}
catch (UnsupportedLookAndFeelException e) {}
SwingUtilities.updateComponentTreeUI(this);
Object[][] rowData = { { "a", "c" }, { "b", "b" }, { "c", "a" } };
Object[] columnHeaders = { "Header1", "Header2" };
model = new FooTableModel(rowData, columnHeaders);
table = new JTable(model);
table.setAutoCreateRowSorter(true);
table.getTableHeader().addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
model.sortByColumn(table.columnAtPoint(evt.getPoint()));
}
});
Container c = getContentPane();
c.add(new JScrollPane(table), BorderLayout.CENTER);
pack();
setVisible(true);
}
public static void main(String[] args) {
new JTableExample();
}
class FooTableModel extends DefaultTableModel {
public FooTableModel(Object[][] rowData, Object[] headers) {
super(rowData, headers);
}
public void sortByColumn(final int clm) {
Collections.sort(this.dataVector, new Comparator() {
public int compare(Object o1, Object o2) {
Vector v1 = (Vector) o1;
Vector v2 = (Vector) o2;
String s1 = (String) v1.get(clm);
String s2 = (String) v2.get(clm);
return s1.compareTo(s2);
}
});
}
}
}