Search code examples
javastringswingjtablerowfilter

JTable rowfilter between two dates, same column


How can I implement a RowFilterbetween two dates? The dates are in string format. Is it necessary to change the format to a date format to apply a RegexFilter?

I tried using the following, but failed :

DefaultTableModel model = (DefaultTableModel) easypath.masteBusiness_table.getModel();
easypath.masteBusiness_table.setModel(model);
TableRowSorter<TableModel> rowSorter = new TableRowSorter<>(easypath.masteBusiness_table.getModel());
easypath.masteBusiness_table.setRowSorter(rowSorter);
rowSorter.setRowFilter(RowFilter.regexFilter(startD+"\\s+(.*?)\\s+"+endD));

I know I am wrong with the filtering as (startD+"\\s+(.*?)\\s+"+endD)); is only for searching a single string but as a novice I would very much appreciate any suggestion.

UPDATE
I just saw this (http://docs.oracle.com/javase/7/docs/api/javax/swing/RowFilter.html) where RowSorter<M,I>, M is the model and I is an integer value, which does not match my criteria


Solution

  • You should be storing a Date in the TableModel not a String representation of the date.

    Then you can use a RowFilter.

    Instead of a regex filter you can use an "and" filter with two date filters. Something like:

    List<RowFilter<Object,Object>> filters = new ArrayList<RowFilter<Object,Object>>(2);
    filters.add( RowFilter.dateFilter(ComparisonType.AFTER, startDate) );
    filters.add( RowFilter.dateFilter(ComparisonType.BEFORE, endDate) );
    rf = RowFilter.andFilter(filters);
    sorter.setRowFilter(rf);
    

    Read the Swing tutorial on Sorting and Filtering for more information and working examples on how to use a filter.