For 'icon' columns we add a text + or - for sorting direction in JTable - Java Swing

Java examples for Swing:JTable Column

Description

For 'icon' columns we add a text + or - for sorting direction in JTable

Demo Code


//package com.java2s;

import java.util.List;

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

public class Main {
    /** For 'icon' columns we add a text + or - for sorting direction */
    public static String getSortText(JTable table, int column) {
        SortKey sortKey = getSortKey(table, column);
        if (sortKey != null
                && table.convertColumnIndexToView(sortKey.getColumn()) == column) {
            switch (sortKey.getSortOrder()) {
            case ASCENDING:
                return "-";
            case DESCENDING:
                return "+";
            }/*  w ww  .  j a v a  2 s.  c om*/
        }
        return "";
    }

    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