Sorts the table using the values in the specified column and sorting order. sortedColumn is the column used for sorting the data. ascending is the sorting order.
()
| 735 | * ascending is the sorting order. |
| 736 | */ |
| 737 | public void sort(){ |
| 738 | try { |
| 739 | if (sortedColumn >= columnData.size()) { return; } |
| 740 | //save the selection |
| 741 | int[] rows = getSelectedRows(); |
| 742 | //convert to model co-ordinates |
| 743 | for(int i = 0; i < rows.length; i++) rows[i] = rowViewToModel(rows[i]); |
| 744 | //create a list of ValueHolder objects for the source data that needs |
| 745 | //sorting |
| 746 | List<ValueHolder> sourceData = |
| 747 | new ArrayList<ValueHolder>(sourceModel.getRowCount()); |
| 748 | //get the data in the source order |
| 749 | for(int i = 0; i < sourceModel.getRowCount(); i++){ |
| 750 | Object value = sourceModel.getValueAt(i, sortedColumn); |
| 751 | sourceData.add(new ValueHolder(value, i)); |
| 752 | } |
| 753 | |
| 754 | //get an appropriate comparator |
| 755 | Comparator<?> comparator = columnData.get(sortedColumn).comparator; |
| 756 | if(comparator == null){ |
| 757 | //use the default comparator |
| 758 | if(defaultComparator == null) defaultComparator = new ObjectComparator(); |
| 759 | comparator = defaultComparator; |
| 760 | } |
| 761 | compWrapper.setComparator(comparator); |
| 762 | //perform the actual sorting |
| 763 | Collections.sort(sourceData, compWrapper); |
| 764 | //extract the new order |
| 765 | for(int i = 0; i < sourceData.size(); i++){ |
| 766 | int targetIndex = i; |
| 767 | int sourceIndex = sourceData.get(i).index; |
| 768 | sourceToTarget[sourceIndex] = targetIndex; |
| 769 | targetToSource[targetIndex] = sourceIndex; |
| 770 | } |
| 771 | sourceData.clear(); |
| 772 | //the rows may have moved about so we need to recalculate the heights |
| 773 | componentSizedProperly = false; |
| 774 | //this deletes the JTable row model |
| 775 | fireTableDataChanged(); |
| 776 | //we need to recreate the row model, and only then restore selection |
| 777 | resizeAndRepaint(); |
| 778 | //restore the selection |
| 779 | clearSelection(); |
| 780 | for(int i = 0; i < rows.length; i++){ |
| 781 | rows[i] = rowModelToView(rows[i]); |
| 782 | if(rows[i] > 0 && rows[i] < getRowCount()) |
| 783 | addRowSelectionInterval(rows[i], rows[i]); |
| 784 | } |
| 785 | }catch(ArrayIndexOutOfBoundsException aioob) { |
| 786 | //this can happen when update events get behind |
| 787 | //just ignore - we'll get another event later to cause the sorting |
| 788 | } |
| 789 | } |
| 790 | /** |
| 791 | * Converts an index from the source coordinates to the target ones. |
| 792 | * Used to propagate events from the data source (table model) to the view. |
no test coverage detected