如何重置JTable列箭头
我正在为我的 JTable 使用可排序的列:
table.setAutoCreateRowSorter(true);
问题是在用户单击列标题后无法删除箭头。即使我删除了表中的所有行。
我试图做相反的事情,但没有奏效:
table.setAutoCreateRowSorter(false);
回答
箭头没有被移除的事实似乎是一个绘画问题。呼叫table.getTableHeader().repaint()似乎使箭头消失。
完整示例:
public class JTableSortRestore {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
runGui();
});
}
private static void runGui() {
JFrame frame = new JFrame("");
frame.setLayout(new BorderLayout());
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Col");
model.addRow(new String[] { "BBB" });
model.addRow(new String[] { "AAA" });
model.addRow(new String[] { "CCC" });
JTable table = new JTable(model);
table.setAutoCreateRowSorter(true);
frame.add(new JScrollPane(table));
JButton restoreButton = new JButton("Restore sorting");
restoreButton.addActionListener(e -> {
table.setAutoCreateRowSorter(false);
table.setAutoCreateRowSorter(true);
table.getTableHeader().repaint();
});
frame.add(restoreButton, BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}