Java SE 6 ASC / DESC的箭头高于Header-Text(必须由客户提供)
我用来在标题文字上面显示箭头:
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);
}
});
}
}
}
答案 0 :(得分:2)
无论您的问题究竟是什么(很难从您的描述中得知),您正在进行错误的排序:在Swing JTable中,排序被认为是视图的责任(与实现中的模型相对)。
自定义比较器(每列)在rowSorter中配置,类似于:
table.setAutoCreateRowSorter(true);
((TableRowSorter) table.getRowSorter()).setComparator(columnIndex, myComparator);
BTW:排序图标的位置由LAF控制,你可以做多少改变(没有写自定义LAF)