Sorting JTable programmatically
Works fine for me:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableBasic extends JPanel
{
public TableBasic()
{
String[] columnNames = {"Date", "String", "Integer", "Boolean"};
Object[][] data =
{
{new Date(), "A", Integer.valueOf(1), Boolean.TRUE },
{new Date(), "B", Integer.valueOf(2), Boolean.FALSE},
{new Date(), "C", Integer.valueOf(19), Boolean.TRUE },
{new Date(), "D", Integer.valueOf(4), Boolean.FALSE}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
// Returning the Class of each column will allow different
// renderers and editors to be used based on Class
public Class getColumnClass(int column)
{
switch (column)
{
case 0: return Date.class;
case 2: return Integer.class;
case 3: return Boolean.class;
}
return super.getColumnClass(column);
}
};
JTable table = new JTable(model);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.setAutoCreateRowSorter(true);
// DefaultRowSorter has the sort() method
ArrayList<RowSorter.SortKey> list = new ArrayList<>();
DefaultRowSorter sorter = ((DefaultRowSorter)table.getRowSorter());
sorter.setSortsOnUpdates(true);
list.add( new RowSorter.SortKey(2, SortOrder.ASCENDING) );
sorter.setSortKeys(list);
sorter.sort();
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane );
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Table Basic");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TableBasic());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
SwingUtilities.invokeLater( () -> createAndShowGUI() );
}
}
Next time post your minimal, reproducible example when something doesn't work.
You also can trigger row sorting by calling toggleSortOrder()
on the RowSorter
of your JTable
:
table.getRowSorter().toggleSortOrder(columnIndex);
Note, however, that (quoting the Javadoc):
Reverses the sort order of the specified column. Typically this will reverse the sort order from ascending to descending (or descending to ascending) if the specified column is already the primary sorted column.
Though it is quicker, calling setSortKeys()
as shown by @camickr (+1 to him) is the correct way to go (but you need to instanciate a List
).