package com.tutego.insel.ui.table;

import java.util.Comparator;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class TableWithRowSorter
{
  public static void main( String[] args )
  {
    TableModel model = new DefaultTableModel( 100, 3 ) {
      @Override public Object getValueAt( int row, int column ) {
        return "" + (int) Math.pow( row, column + 1 );
      } 
    };
    JTable table = new JTable( model );

    TableRowSorter<TableModel> rowSorter = new TableRowSorter<TableModel>( model );
    table.setRowSorter( rowSorter );

    rowSorter.setComparator( 0, new Comparator<String>() {
      public int compare( String s1, String s2 )
      {
        int i1 = Integer.parseInt( s1 ), i2 = Integer.parseInt( s2 );
        return Integer.bitCount( i1 ) - Integer.bitCount( i2 ); 
      }
    } );
    rowSorter.setSortable( 1, false );
//    rowSorter.sort();

    rowSorter.setRowFilter( RowFilter.regexFilter("(0|2|4|6|8)$", 2) );

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.add( new JScrollPane(table) );
    frame.pack();
    frame.setVisible( true );
  }
}
