I'm using sortable columns for my JTable:
table.setAutoCreateRowSorter(true);
The issue is that after the user click on a column header there's no way to remove the arrow. Even If I delete all the rows in the table.
I tried to do the opposite but it didn't work:
table.setAutoCreateRowSorter(false);
The fact the arrow is not removed seem to be a painting issue. Calling table.getTableHeader().repaint()
seems to make the arrow go away.
Full example:
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);
}
}