is there any way how to get which column of JTable is sorted and what is sort orientation?
Thanks.
is there any way how to get which column of JTable is sorted and what is sort orientation?
Thanks.
Use JTable.getRowSorter() to get the RowSorter.
Then call getSortKey(). The SortKey will tell you what you want to know.
/**
* Returns an array with the indices of the sorted colummns. The array
* returned is sorted from high priority to low priority. In case there
* are less than 3 sorted columns or there aren't RowSorter the values
* in the returned array will be -1
* @param table
* @return array of length 3 with columns indices order by the highest priority descending.
*/
public static int[] getTableSortedColumns(JTable table){
int[] index = new int[]{-1,-1,-1};
List<? extends SortKey> rowSorter = table.getRowSorter().getSortKeys();
Iterator<? extends SortKey> it = rowSorter.iterator();
int i = 0;
while(it.hasNext()){
SortKey sortKey = it.next();
if(sortKey.getSortOrder().compareTo(SortOrder.UNSORTED)!=0 ){
index[i] = sortKey.getColumn();
i++;
}
}
return index;
}
/**
* Return the sort orientation of a column.
* @param table
* @param columnIndex
* @return int i == ascending, -1 == descending, 0 == unsorted
*/
public static int getTableSortedOrientation(JTable table, int columnIndex){
int[] indices = getTableSortedColumns(table);
int orientation = 0;
for(int i = 0;i<indices.length;i++){
if(indices[i] == columnIndex){
SortOrder so = table.getRowSorter().getSortKeys().get(i).getSortOrder();
if(so.compareTo(SortOrder.ASCENDING) == 0){
orientation = 1;
}else if(so.compareTo(SortOrder.DESCENDING) == 0){
orientation = -1;
}
}
}
return orientation;
}
Use Example :
int[] col = YourClass.getTableSortedColumns(jTable);
for(int i = 0;i<col.length;i++){
if(col[i]>=0){
String orientation = "";
switch(YourClass.getTableSortedOrientation(jTable, col[i])){
case 1:
orientation = "Ascending";
break;
case 0:
orientation = "Unsorted";
break;
case -1:
orientation = "Descending";
break;
}
System.out.println("index "+col[i]+" "+orientation);
}
}