Java - JTable - как получить, какой столбец сортируется и сортировать ориентацию? - PullRequest
1 голос
/ 10 декабря 2011

есть ли способ узнать, какой столбец JTable отсортирован и какова ориентация сортировки?

Спасибо.

Ответы [ 3 ]

4 голосов
/ 10 декабря 2011

Используйте JTable.getRowSorter(), чтобы получить RowSorter.

Затем позвоните getSortKey().SortKey скажет вам, что вы хотите знать.

0 голосов
/ 26 октября 2016
 /**
 * 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;
}

Пример использования:

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);
        }
    }
0 голосов
/ 10 декабря 2011
  • Перейдите в документ API для JTable
  • Используйте функции текстового поиска в браузере для поиска «сортировки»
  • find JTable.getRowSorter()
  • readподробности там.
...