简体   繁体   中英

Resort JTable Rows Programmatically(only) when new Row is Added

I Have a JTable which i I need to resort the rows when a new row is added automatically.

But the Table cannot be allowed to have the sorting functionality by clicking the header active.

Normally when i load the table for the first time i can sort the rows by sorting the list of the data before hand.

Comparator<Map.Entry<FieldDescriptor, Object>> c = new Comparator<Map.Entry<FieldDescriptor, Object>>() {
    public int compare(Map.Entry<FieldDescriptor, Object> o1, Map.Entry<FieldDescriptor, Object> o2) {
        return o1.getKey().getName().compareTo(o2.getKey().getName());
    }
};

List<Map.Entry<FieldDescriptor, Object>> lSet = eSet.stream().collect(Collectors.toList());
Collections.sort(lSet, c);

And this works fine because when i add the rows to the table for the first time, because the list is already sorted, and they come on the correct order.

But if a new row is added afther the table is filled i need to reorder the rows correctly.

But the Table cannot be allowed to have the sorting functionality by clicking the header active.

Why? Requirements like this never make sense. Why do you need to limit what a user can do?

In any case you should still be able to do what you want by using the DefaultRowSorter . Read the API for the various methods.

There is no need to sort the external List. Leave all the sorting up to the sorter.

To do the initial sort when the table is create the logic might be something like:

table.setModel(...);
table.setAutoCreateRowSorter(true);
DefaultRowSorter sorter = (DefaultRowSorter)table.getRowSorter();
sorter.setSortsOnUpdates( true );
sorter.toggleSortOrder(2); // initially sort on this column

sorter.setSortable(0, false); // disable sorting on all columns 
sorter.setSortable(1, false);
...

Now when you add a row of data the logic might be:

sorter.setSortable(2, true);
model.addRow(...);
sorter.setSortable(2, false);

Or maybe you can just disable sorting on all the columns except the sorted column, then you don't need to worry about the above logic. This would then all the user to toggle the sort order between ascending/descending on the one column.

I wouldn't use the row sorter functionality of the JTable but rather have a TableModel that automatically put the new row in the correct position.

For example if you use DefaultTableModel, find where the row should be added and use insertRow method: https://docs.oracle.com/en/java/javase/14/docs/api/java.desktop/javax/swing/table/DefaultTableModel.html#insertRow(int,java.lang.Object%5B%5D)

The JTable should then update automatically with the new row at the correct position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM