Get JTable sorting Icon - Java Swing

Java examples for Swing:JTable Sort

Description

Get JTable sorting Icon

Demo Code


//package com.java2s;

import java.util.List;
import javax.swing.Icon;

import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.RowSorter.SortKey;
import javax.swing.UIManager;

public class Main {
    /** Code taken from open source example on web:
     * http://tips4java.wordpress.com/2009/02/27/default-table-header-cell-renderer/
     * /*w  ww  .j a v a 2 s . c om*/
     * This might move into IconFactory
     */
    public static Icon getIcon(JTable table, int column) {
        SortKey sortKey = getSortKey(table, column);
        if (sortKey != null
                && table.convertColumnIndexToView(sortKey.getColumn()) == column) {
            switch (sortKey.getSortOrder()) {
            case ASCENDING:
                return UIManager.getIcon("Table.ascendingSortIcon");
            case DESCENDING:
                return UIManager.getIcon("Table.descendingSortIcon");
            }
        }
        return null;
    }

    public static SortKey getSortKey(JTable table, int column) {
        RowSorter rowSorter = table.getRowSorter();
        if (rowSorter == null) {
            return null;
        }

        List sortedColumns = rowSorter.getSortKeys();
        if (!sortedColumns.isEmpty()) {
            return (SortKey) sortedColumns.get(0);
        }
        return null;
    }
}

Related Tutorials