Ethan Mick
Ethan Mick

Reputation: 9567

Sort JTable column of longs

I'm trying to sort a column in my JTable. The column contains Long's (java.util.Long), which implement Comparable. Therefore, reading this document, it says:

1: If a Comparator has been specified for the column by the setComparator method, use it.

2: If the column class as returned by getColumnClass is String, use the Comparator returned by Collator.getInstance().

3: If the column class implements Comparable, use a Comparator that invokes the compareTo method.

4: If a TableStringConverter has been specified, use it to convert the values to Strings and then use the Comparator returned by Collator.getInstance().

5: Otherwise use the Comparator returned by Collator.getInstance() on the results from calling toString on the objects.

My code does not create a custom Comparator object, so #1 is out. The column is a column of Long's so #2 is out. #3 states that it should sort by the Long "compareTo" method. But it doesn't. If my JTable has 3 Longs, 90,900, and 111, it will sort them, "900,90,111" or "111,90,900". It appears to be sorting them like strings, as stated in #5.

Here is out we create our table:

table = new JTable( new CustomTableModel( new Vector<Vector<Object>>() ,Record.getNames() ) );
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setAutoCreateRowSorter(true);

And then adding info:

public void setRecords( Iterable<Record> records ){
    CustomTableModel model = (CustomTableModel) table.getModel();
    model.setRowCount(0);
    model.clearRecords();

    for( Record r : records ){
        Vector<Object> v = new Vector<Object>();
        v.add(r.getFromNumber());
        v.add(r.getToNumber());
        v.add(r.getStartDate());
        v.add(new Long( r.getDuration() ) );
        model.addRow(v);
        model.addRecord(r);
    }
    model.fireTableDataChanged();
    table.getRowSorter().toggleSortOrder(2);

How can I fix it, so the last column (column 3), is sorted by Long/long/int, and not by string? I looked into custom comparators, but I wasn't sure how to implement. Shouldn't the JTable use #3? Thanks!

Upvotes: 1

Views: 850

Answers (1)

trashgod
trashgod

Reputation: 205855

Verify that your model's getColumnClass() method returns Long.class.

Upvotes: 1

Related Questions